Dr. Tim Margush
University of Akron
© 2005
• Understand the collection objects ArrayList and Array
– Know their differences and why to choose one over the other
• Learn some common array algorithms
• Be familiar with common representations of collections inside arrays
• Be able to use 2-dimensional arrays
© 2005 Dr. Tim Margush
• A generic collection class designed to hold a heterogeneous list of references to objects
– Behavior: ability to add, remove, and access collection elements
– State: knows how many elements
• Elements are stored by position ( index )
– Positions range from 0 through list.size()-1
– Use of an illegal index causes an exception
© 2005 Dr. Tim Margush
ArrayList<String> one = new ArrayList<String>();
ArrayList<Rectangle> two = new ArrayList<Rectangle>(50);
• The class type in brackets
< > specifies the type of objects each ArrayList will hold
– You may not specify a primitive type such as int
• The optional int argument specifies the initial capacity for the collection
– The default initial capacity is 10
• ArrayLists expand as needed, but expanding is costly, so choosing an initial capacity may increase efficiency
– You can manually expand using the ArrayList's ensureCapacity(int minCapacity) method
– You can shrink a list using trimToSize()
© 2005 Dr. Tim Margush
• Add to the end of a list (append)
– one.add("Joe"); //string literal becomes a String object
• Add at the specified index (shifts displaced elements to higher locations)
– two.add(index, new Rectangle());
• An exception occurs if index<0 or index>two.size()
• You may only add objects whose type matches the
ArrayList type parameter
– two.add("whatever"); is illegal
© 2005 Dr. Tim Margush
• The get method returns a reference to an
Object in the collection
– You must specify a legal index
String n = one.get(0);
Rectangle t = two.get(two.size()-1);
• Illegal locations such as two.size() or -1 will cause exceptions
© 2005 Dr. Tim Margush
• Before Java 1.5, ArrayLists were not parameterized
– ArrayList old = new ArrayList();
• Any object type could be added to any list
– old.add("Fred"; old.add(new Rectangle());
• Retrieving returned an Object type, and required casting
– String a = (String)old.get(0);
•
Use the parameterized lists in new code development
© 2005 Dr. Tim Margush
•
ArrayLists can not hold primitive data; a wrapper object must be used
– ArrayList<Integer> three = new ArrayList<Integer>();
• Java 1.5 supports automatic casts (coercion) between primitive data and their wrapper class
– three.add(7); auto-boxes 7 as an Integer (instead of int )
• Equivalent to: three.add(new Integer(7));
• A reference to the Integer object is stored in the list
– int y = three.get(0); auto-unboxes the Integer object to the primitive value used in the assignment
• Equivalent to: int y = three.get(0).intValue();
© 2005 Dr. Tim Margush
• Use the set method to replace an object at a particular location (this location must exist) one.set(0, "New Value"); two.set(two.size()-1, null);
• Use the remove method to remove an item, reducing the size of the list
– Items at higher positions "slide over" to new locations
(each index is decreased by one) two.remove(legalIndex);
– removeRange(from, to) can be used to delete a section of a list (removes items at from through to-1 )
– clear() removes all elements
© 2005 Dr. Tim Margush
• An indexed, homogeneous collection of primitive data or object references
• Arrays are declared using a type followed by brackets (i.e. int[] x; Object[] y)
– Some prefer int x[]; or Object y[];
• int[] x, y; declares 2 arrays to hold ints
• int x[], y; declares only one array, and an int variable
• Array types are subclasses of Object
– Java contains a utility class named
Arrays , but this is a collection of static methods to manipulate arrays
© 2005 Dr. Tim Margush
• Arrays are objects, created using the new operator
– The length of the array must be specified when it is created, and cannot be changed: int [] x = new int[20];
Object[] y = new Object[3];
– Array lengths are of type int and are non-negative
– Array elements (contents) are auto-initialized
• Array elements are accessed using the array access operator: x[0] = 7; x[19] = -54;
String oh = y[2].toString(); y[0] = new Rectangle();
© 2005 Dr. Tim Margush
• Arrays can be instantiated implicitly by specifying a list of values
String[] names = {"Joe", "Fred", "Tom"};
Object[] shapes = {new Rectangle(), new Triangle()}; int[] numbers = { };
• This is only allowed at the point of declaration so the following are illegal names = {"Steve", "Sam"}; numbers = {1, 2, 3, 4, 5};
© 2005 Dr. Tim Margush
• Java allows specification of an initialized array to be passed when an Array object is created, so
String [] names; names = {"Steve", "Sam"}; //illegal names = new String[] {"Fred", "Sally", "Caleb"}; //OK dumb = new int[] {1, 2, 3, 4, 5}; //OK
//assuming someMethod takes a char [] argument: someClass.someMethod( new char[] {'a', 'e', 'i', 'o', 'u'} );
© 2005 Dr. Tim Margush
• Arrays know how many elements they contain (and of course their contents) public static void main(String[] args){ for (int i=args.length-1; i>=0; i--){
System.out.println(args[i]);
– The array's length is not a method; it is a final public instance member
– Legal array subscripts range from 0 through theArray.length-1
• Using an illegal subscript results in an exception
© 2005 Dr. Tim Margush
• Arrays of primitives actually contain the primitive values
– int[] x = {2, 5, 9}; x:
• Arrays of an object type contain references
– String[] names = {"Joe", "Fred", "Ann"}; names:
ArrayList objects always contain
Object references
--references can be null
Joe
Fred
Ann
2
5
9
© 2005 Dr. Tim Margush
• Arrays are Objects; Object has a clone method
– int[] x = {3, 6, 9, 11};
– int[] y;
– y = (int[]) x.
clone ();
• The System object has an arraycopy method suitable for copying some or all elements in an array to an existing array
– int[] z = new int[x.length-1];
– //copy z.length elements from x (start at index 1)
– // to z (start at index 0)
– System.
arraycopy (x, 1, z, 0, z.length);
© 2005 Dr. Tim Margush
• When an array contains object references, you are only copying references
Employee[] a, b; …
System.arraycopy(a, 0, b, 0, a.length); //shallow copy b[2].changeWage(20.55); //changes a[2] also
• Using the Object clone method also creates a new array of references, but there is only one set of employees b = (Employee[]) a.clone(); //shallow copy a[2].changeWage(15.00); //changes b[2] also
© 2005 Dr. Tim Margush
• Since Arrays are fixed-length storage containers, it is common to use only part of the array
– An auxiliary int variable (such as numItems) is often used to keep track of the number of locations in use
• double[] theArray d = new double[40];
• int numItems = 0; //numItems <= theArray.length
–
"In use" locations commonly start at 0 and go through numItems-1
© 2005 Dr. Tim Margush
• Adding to the end of an array d[numItems++] = 3.6;
• Removing the last item in an array numItems--;
– the item is still in the array, but we consider the position unused
• Getting and removing the last element double last = d[--numItems];
© 2005 Dr. Tim Margush
• Slide elements down one position (similar to remove element at index i)
– The element at i is overwritten
– The array length is unchanged int i=3;
System.arraycopy(y, i+1, y, i, numItems-i-1); numItems--;
4 11 8 7 9 2 8
4 11 8 9 2 8 8
© 2005 Dr. Tim Margush
In this case, copying begins at index 4
(copied to index
3) and proceeds left to right
• Slide elements up one position (similar to add at index i)
– The element at index i can be overwritten after the copy is complete int i=3; numItems++;
System.arraycopy(y, i, y, i+1, numItems-i-1);
4 11 8 9 2 8 8
4 11 8 9 9 2 8
© 2005 Dr. Tim Margush
In this case, copying begins at index 5
(copied to index
6) and proceeds right to left
• Arrays are fixed-length containers, so if more capacity is needed, we must get a new and larger container
– Here the array size is doubled (plus 1 in case original was 0)
– Old contents are copied to the new array
– The old array will be discarded after the method call completes
} private String[] names = {}; private int numNames = 0;
//Add a name public void add(String newName){ if (numNames==names.length){
String[] old = names; names = new String[2*names.length+1];
System.arraycopy
(old,0, names,0, numNames);
} names[numNames++]=newName;
© 2005 Dr. Tim Margush
• For a collection whose size is known and where efficiency is important, use an Array
– This usually requires the auxiliary numItems variable
• When the array size may need to expand…
– For collections of primitives, the Array is more efficient and convenient, use the grow technique shown earlier
– Collections of objects are just as easily (and as efficiently) managed in an ArrayList
© 2005 Dr. Tim Margush
• Problem: Determine if a particular element is present in a list
– Subproblem: If present, determine its location
• Solution: Sequential search
– Examine list items sequentially until the item is found, or all items have been eliminated
• ArrayList objects support these operations
– public boolean contains(Object x)
– public int indexOf(Object x)
• The equals method is used to compare objects, so be sure to overload it for the objects in your collection!
© 2005 Dr. Tim Margush
} private String[] list; private int numItems; public boolean contains(String target){ int loc = 0; while (loc<numItems && !list[loc].equals(target)) loc++; return loc < numItems; //true if found
© 2005 Dr. Tim Margush
} private int[] list; private int numItems; public int max(){ //precondition: numItems>0 if (numItems==0) return 0; //throw exception instead?
int max = list[0]; //use first item as initial max estimate for (int i = numItems-1; i>0; i--) if (list[i] > max) max = list[i]; return max;
© 2005 Dr. Tim Margush
private int[] list; public int max(){
//precondition: all elements are in use
}
//and list.length is at least 1 int max = list[0]; //use first item as initial max estimate for (int item : list ) if (item > max) max = item; return max;
These algorithms could be applied to ArrayLists as well
© 2005 Dr. Tim Margush
• The enhanced for (sometimes called for each ) can be used with Arrays or ArrayLists
– The iteration visits all elements of the structure
– The iteration goes from first to last
– The loop does not know what position is being examined for (type variablename : collectionname) statement;
© 2005 Dr. Tim Margush
• An array stores one column of information
• When two or more columns must be stored, parallel arrays are sometimes used
String[] name, tele;
– name[n] has tele[n]
Joe Thomas
Sally Harmon
…
330-555-1212
330-999-0099
…
• Such structures can be more elegantly implemented using objects:
} class NameNumber{ private String name, tele;
…
NameNumber[] contacts; or
ArrayList<NameNumber> contacts;
© 2005 Dr. Tim Margush
• Since each element of an array (often called a row ) can hold an object reference, it is possible to refer to another array.
– When a row is another array, its components are called columns
– This organization gives a 2dimensional feel (rows and columns) to the outer array double[][] x = new double[3][4]; x: rows
© 2005 Dr. Tim Margush
3.5
2.6
-9.1 0.6
0.7
-9.1 2.0
1.1
2.5
0.1
0.2
6.4
columns
System.out.println(x[1][3]);
//displays 1.1
x[0][0] = 1.5;
//changes 3.5 to 1.5
• Each row can be a different size array
– This is sometimes called a ragged array
• Additional dimensions are allowed (to any depth)
String[][][][] z = new String[2][3][2][4];
– //try drawing this!!!
int[][] x = new int[3][]; x: rows
2 8 7 1
0 0
2 8 7 1 columns x[0] = new int[] {2, 8, 7, 1}; x[1] = new int[2]; x[2] = (int[]) x[0].clone() x[1][1] = 5;
© 2005 Dr. Tim Margush
• Arrays and ArrayLists hold sequences of items indexed by an int
– ArrayLists only hold Objects (references)
– Arrays can hold primitives or object references
• ArrayLists are variable in size and capacity and provide info about the current size
• Arrays have a fixed length (capacity) and do not provide info about how much is in use
© 2005 Dr. Tim Margush
• Array and ArrayList indices start at 0
• Parallel arrays are better implemented using one array of objects
– Each object encapsulates a row of the parallel structure
• Multidimensional arrays can be used to represent tables or more complex hierarchical structures
© 2005 Dr. Tim Margush