Title: Objects for Organizing Data
1Objects for Organizing Data --
- As our programs get more sophisticated, we need
assistance organizing large amounts of data. - array declaration and use
- arrays of objects
- parameters and arrays
- multidimensional arrays
- the ArrayList class
- additional techniques for managing strings
2Arrays
- An array is an ordered list of values each of
which has their own position within the array. - It is a collection of variables that share the
same name. - Each value/variable has a numeric index or
subscript to refer to a particular element in the
array.
3Arrays
- For example, an array element can be assigned a
value, printed, or used in a calculation - scores2 89
- scoresfirst scoresfirst 2
- mean (scores0 scores1)/2
- System.out.println ("Top " scores5)
4Arrays
- An array of size N is indexed from zero to N-1
- The following array of integers has a size of 10
and is indexed from 0 to 9
5ARRAYS
- When an array is declared, the name of the array
is the address in memory of the first value in
the array. For instance, an array of 9 integers
(indexed 0-8) called intArray would be located in
memory like this
View of Memory
1 Location 23
90
40
60 70
75 80 90
scores
01
2
3
4
5
6
7 8
6Arrays
- An array stores multiple values of the same data
type. - So if an array of integers is declared, only
integers may be stored in that array, no strings
or characters. - The type can be primitive types or objects.
- Primitive types include arrays of integers,
doubles, chars, longints etc. - Therefore, we can create an array of integers, or
an array of characters, or an array of String
objects, etc.
7Arrays
- In Java, the array itself is an object.
Therefore - Any of the methods that can be used on an object
can be used on an array. - The name of the array is a reference variable,
and the array itself is instantiated separately.
8Declaring Arrays
- Since arrays are objects, the reference must
first be declared and then the array can be
instantiated. - The scores array could be declared as follows
- int scores new int10
-
- Note that the type of the array (int) does not
specify its size, but the new operator reserves
memory locations to store 10 integers indexed
from 0 to 9.
9Arrays
- The type of the variable scores is int (an
array of integers) - It is set to a newly instantiated array of 10
integers. Only integers may be stored in this
array. - If we declared an array of strings, only strings
may be stored in that array.
10Declaring Arrays
- Some examples of array declarations
- float prices new float500
- boolean flags
- flags new boolean20
- char codes new char1750
- int intArray //allocates no memory
11Arrays
- You cannot access an index of an array until it
is instantiated. -
- int grades // grades Array has no memory
allotted -
- grades3 7 // ERROR - grades3 does not
yet exist
12Creates an array with 10 elements
- class Basic_Array
- final static int LIMIT 10 // value will
not change as
final static int INCREMENT 10 // only
one copy needed - public static void main (String args)
intlist
new intLIMIT for(int index 0 index lt
LIMIT index)
listindex index INCREMENT - list5 999
- for (int value list) // forEach value in
list - System.out.print (value " ")
// method main // stores increments of 10
in each element -
130 10
20
30
40 50
60 70
80 90
01
2
3
4
5
6
7
89
0 10
20
30
40 999
60 70
80 90
01
2
3
4
5
6
7
89
Element index 5 is change to 999, which is the
6th element in the array.
14Arrays
- The constant LIMIT holds the size of the array.
This is a good programming technique because it
allows you to change the size of the array in one
place - at the beginning of the program. - The square brackets in the array declaration are
an operator in Java. They have a precedence
relative to other operators i.e. the highest
precedence. - Both constants in the previous example were
declared static because only copy of the size of
the array is needed. -
15Bounds Checking
- If the array codes can hold 100 values, it can
only be indexed using the numbers 0 to 99 - If count has the value 100, then the following
reference will cause an ArrayOutOfBoundsException
- System.out.println (codescount)
- Its common to introduce off-by-one errors when
using arrays
for (int index0 index lt 100
index) codesindex index50 epsilon
16Bounds Checking
- Each array object has a public constant called
length that stores the size of the array. - It is referenced through the array name (just
like any other object)
17Length of an Array
- scores.length
- Length is a constant defined in the array class.
- scores. length holds the number of elements
allocated, not the largest index. - That is, it holds the number of items you
allocated for the array when you declared it.. - In the program Reverse_Numbers, an array is
constructed to store numbers which are printed
out in reverse.
18ARRAYS
- Arrays are considered to be a static structure
because they have a fixed size. They cannot
shrink or grow in size. - Data structures like arrays are good when we
know ahead of time how many elements are needed.
- Other data structures like ArrayLists and linked
lists can be used when it is necessary to
dynamically build a structure to hold elements. - This is necessary when the number of elements is
not known ahead of time.
19Initializer Lists
- An initializer list can be used to instantiate
and initialize an array in one step. - The values are delimited by braces and separated
by commas. Examples - int units 147, 323, 89, 933, 540,
- 269, 97, 114, 298, 476
- char letter_grades 'A', 'B', 'C',D
-
The array units is instantiated
as an array of 10 ints, indexed from 0 to 9. -
- The letter_grades array consists of an array of 4
characters.
20Initializer Lists
- Note that when an initializer list is used
- the new operator is not used
- no size value is specified
- the type of each value in the list must be the
same as the data type of the array. - The size of the array is determined by the number
of items in the initializer list. An initializer
list can only be used in the declaration of an
array. - The array size is set to the number of elements
in the initializer list.
21INITIALIZING ARRAYS
- When an array object is instantiated, the
elements in the array are initialized to the
default value of the indicated data type. - That is, it you declare an array of integers,
each element is initialized to 0. -
- However, it is always better to do your own
initialization.
22Array Examples
- int Numbers new int100
Numbers0
0 - for(int i 1 i lt Numbers.length i)
Numbersi i Numbers(i-1 - We used the length field, which is the field
provided in the array class to contain the length
of the array. This field is read-only. - Though arrays are objects and can access all the
methods that objects can, the syntax associated
with them is somewhat different from that of
other objects.
23CLASS SUM
- class Sum public static void
main(String args )
int intArray 1, 3, 5,
4, 7, 2, 16, 99, 45, 67
int total 0
// accumulate the total of the elements in
the array for
(int j 0 j lt intArray.length j)
total total intArrayj
//
print results System.out.println( Total
array elements is , total) - // method main // class Sum
- output Total of array elements is 287
24ArrayCopy
- It is possible to copy one array to another array
with the arraycopy method -
- public static void arraycopy(Object sourceArray,
int srcIndex, Object destination, int destIndex,
int length). - The two objects are the source and destination
arrays, the srcIndex and destIndex are the
starting points in the source and destination
arrays, and length is the number of elements to
copy. E.g.
25Copying Arrays
- public static void main(String args)
char copyFrom d,e,c,a, f,
f,e,i n char
copyTo new char7
System.arraycopy(copyFrom, 2, copyTo, 0,7)
- Arraycopy method begins the copy at element
number 2 in the source array (copyFrom) which is
element c. It copies it to the destination
array (copyTO) starting at index 0. It copies 7
elements, c to n into copyTO.
2
d e c a f f e i n
copyFrom
0 1 2 3 4 5 6
c a f f e i n
copyTO
26Arrays of Objects
- Objects can have arrays as instance variables.
Therefore, fairly complex structures can be
created simply with arrays and objects - The software designer must carefully determine an
organization for each application.
27ARRAYS
- The elements of an array can be object
references. The declaration -
String words new String25 - reserves space to store 25 references to String
objects. - It does NOT create the String objects themselves
28Arrays of Objects
- The words array when initially declared
- At this point, the following reference would
throw a NullPointerException - System.out.println (words0)
29Arrays of Objects
- After some String objects are created and stored
in the array
Address of string
30Arrays of Objects
- Keep in mind that String objects can be created
using literals - The following declaration creates an array object
called verbs and fills it with four String
objects created using string literals
String verbs "play", "work", "eat", "sleep"
31Initializing Arrays
- // initializes the array
- String name_list Paul, Newman,
Jessica, Ten) - Since a string literal instantiates a new string
object, each string literal in the initializer
list creates an object for each element of the
array. Hence - for(int name 0 name lt name_list.length
name) System.out.printl(name_listname
) - OUTPUT Paul Newman Jessica Ten
32Array of Strings
- Each object stored in an array can also be
instantiated separately. e.g.
String phrase new
String5
phrase0 Good Morning - phrase1 How are you
- phrase2 Have a Good Day
33Arrays of Objects
- The following example creates an array of Grade
objects, each with a string representation and a
numeric lower bound - See GradeRange.java
- See Grade.java
- Now let's look at an example that manages a
collection of CD objects - See Tunes.java
- See CDCollection.java
- See CD.java
34Arrays of Objects
- A UML diagram for the Tunes program
35Outline
Declaring and Using Arrays Arrays of
Objects Two-Dimensional Arrays Variable Length
Parameter Lists The ArrayList Class Polygons and
Polylines Mouse Events and Key Events
36Multidimensional Arrays
- A one-dimensional array stores a simple list of
values. - A two-dimensional array can be thought of as a
table of values, with rows and columns. - A two-dimensional array element is referenced
using two index values. - To be precise, a two-dimensional array in Java is
an array of arrays, therefore each row can have a
different length.
37Two-Dimensional Arrays
- A one-dimensional array stores a list of elements
- A two-dimensional array can be thought of as a
table of elements, with rows and columns
38Two-Dimensional Arrays
- To be precise, in Java a two-dimensional array is
an array of arrays - A two-dimensional array is declared by specifying
the size of each dimension separately - int scores new int1250
- A array element is referenced using two index
values - value scores36
- The array stored in one row can be specified
using one index
39Two-Dimensional Arrays
- See TwoDArray.java (page 399)
- See SodaSurvey.java (page 400)
40Multidimensional Arrays
- int table 28, 84, 47, 72, 69, 26,
91, 40, 28, 42, 34, 37, 13, 26, 57, 35 - The first values - 28, 84, 47 and 72 represent
the first row of the array. The second set of
values are the 2nd row -
- 28 84 47 72
- 69 26
- 91 40 28
- 42 34 37
- 13 26 57 35
41Two Dimensional Arrays
- Actually Java does not support 2d arrays in the
traditional sense. What it does allow are
one-dimensional arrays that hold arrays as
values. - In an initializer list, the first values
represent the first element in the array. 28,
84, 47, 72 - int table 28, 84, 47, 72, 69, 26,
91, 40, 28, 42, 34, 37, 13, 26, 57, 35 - An initializer list can be used to create and set
up a multidimensional array or values can be read
into the array from a file or the keyboard.
42Multi-dimensional Arrays.
- Each element in the list is itself an initializer
list. It is helpful to conceive of the 2D array
as a table and a 3D array as a cube. After that,
it is not easy to conceive of anything. - Note that each array dimension has its own length
constant. You can use the name of the array e.g.
from the previous example - table.length is the
number of rows.
43- public class PassArrays
-
- public static void main(String args)
-
- int grades 100, 79, 83 , 44,
56, 67 , 95, 88, 99
printStudentScores( grades1 )
-
- // To print one row of the TwoD array
public static void
printStudentScores( int row ) -
- System.out.print("Scores for
student ")
for (int i 0 i lt row.length
i) System.out.println(rowi
)
44Creating a Checkerboard
// create the checkerboard Square
checkerboard new SquareMAX_SIZEMAX_SIZE//
Now fill it with square objects int row, col, x
0, y 0 for (row0 row lt
checkerboard.length row) for (col0 col
lt checkerboardrow.lengthcol) // use
some condition that will alternate between red
and black squares // and then create a new
square checkerboardrowcol new
Square(constructor parameters) // now draw
the square calling the appropriate method in the
square class else//Draws other
color squares checkerboardrowcol
new Square(constructor parameters) // now
draw the square calling the appropriate method in
the square class // close else
//close inner for // close outer for // The
code is not complete - you have change the x and
y values as you cross the rows // and when you
move to the next row , change x and y values
45Variable Length Parameter Lists
- Suppose we wanted to create a method that
processed a different amount of data from one
invocation to the next - For example, let's define a method called average
that returns the average of a set of integer
parameters
// one call to average three values mean1
average (42, 69, 37)
// another call to average seven values mean2
average (35, 43, 93, 23, 40, 21, 75)
46Variable Length Parameter Lists
- We could define overloaded versions of the
average method - Downside we'd need a separate version of the
method for each parameter count - We could define the method to accept an array of
integers - Downside we'd have to create the array and store
the integers prior to calling the method each
time - Instead, Java provides a convenient way to create
variable length parameter lists
47Variable Length Parameter Lists
- Using special syntax in the formal parameter
list, we can define a method to accept any number
of parameters of the same type - For each call, the parameters are automatically
put into an array for easy processing in the
method
public double average (int ... list) //
whatever
48Variable Length Parameter Lists
public double average (int ... list) double
result 0.0 if (list.length ! 0)
int sum 0 for (int num list)
sum num result (double)num /
list.length return result
49Variable Length Parameter Lists
- The type of the parameter can be any primitive or
object type
public void printGrades (Grade ... grades)
for (Grade letterGrade grades)
System.out.println (letterGrade)
50Variable Length Parameter Lists
- A method that accepts a variable number of
parameters can also accept other parameters - The following method accepts an int, a String
object, and a variable number of double values
into an array called nums
public void test (int count, String name,
double ... nums) // whatever
51Variable Length Parameter Lists
- The varying number of parameters must come last
in the formal arguments - A single method cannot accept two sets of varying
parameters - Constructors can also be set up to accept a
variable number of parameters - See VariableParameters.java (page 396)
- See Family.java (page 397)
52Arrays as Parameters
- An entire array can be passed to a method as a
parameter. Like any other object, the reference
to the array is passed, making the formal and
actual parameters aliases of each other. - Changing an array element in the method changes
the original element. An array element can be
passed to a method as well, and follow the
parameter passing rules of that element's type.
53The ArrayList Class
- An object of class ArrayList is similar to an
array in that it stores multiple values - However, a ArrayList
- only stores objects.
- can grow and shrink in size
- Service methods provided by the ArrayList t class
are used to interact with a ArrayList..
54The ArrayList Class
- An important difference between an array and a
ArrayList is that a ArrayList can be thought of
as dynamic, that is, it is able to change its
size as needed . - A static structure like an array has a fixed size
throughout its existence. - Each ArrayList initially has a certain amount of
memory space reserved for storing elements.
55ArrayList Class
- If an element is added that doesn't fit in the
existing space, more room is automatically
acquired. - It accomplishes this by creating and destroying
arrays. This is not really efficient except for
representing linear relationships.
56The ArrayList Class
- An ArrayList is implemented using an array.
- Whenever new space is required, a new, larger
array is created, and the values are copied from
the original to the new array. - To insert an element, existing elements are first
copied, one by one, to another position in the
array. - Therefore, the implementation of ArrayList in the
API is not very efficient
57The ArrayList Class
- Elements can be inserted or removed with a single
method invocation - When an element is inserted, the other elements
"move aside" to make room - Likewise, when an element is removed, the list
"collapses" to close the gap - The indexes of the elements adjust accordingly
58ArrayLists
- The major advantage of an ArrayList that we can
store different types of objects in it. - Since the methods are designed to accept
references to any Object type, a reference to a
string, an integer, a double etc. can be passed.
- NOTE that if a primitive type is passed, it
must be passed as an object using the Integer, or
Double wrapper classes.
59ArrayList Class
- Thus to put an integer into an ArrayList you
would have to first create an integer object - Integer num new Integer(2)
Double doublenum new Double(2.98) - The benefits of this are that different kinds of
objects can be stored in the same data structure. - You must inport the java.util package to use an
ArrayList -
60The ArrayList class Service methods
add(Object element) adds element to end of list
remove (Object element)
removes the object from the ArrayList. The
parameter is an alias to the object to be
removed. contains (Object element)
returns true if the object is in the ArrayList.
get (int index) returns the object at the
index specified. ensureCapacity() expands
array by creating a new array. lastIndexOf(Object
element) returns the last occurrence of
element. size() returns the number of objects.
61The ArrayList Class
- An ArrayList stores references to the Object
class, which allows it to store any kind of
object - See Beatles.java (page 405)
- We can also define an ArrayList object to accept
a particular type of object - The following declaration creates an ArrayList
object that only stores Family objects - ArrayList ltFamilygt reunion new ArrayList
ltFamilygt - This is an example of generics to be discussed
later