# ARRAY & ARRAYLIST REVIEW

```Data Structures
and Algorithms I
ArrayList, Array, and
Array Concepts
Dr. Tim Margush
University of Akron
Goals
• 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
java.util.ArrayList
• 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
ArrayList Constructors
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()
• 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)
• An exception occurs if index<0 or index>two.size()
• You may only add objects whose type matches the
ArrayList type parameter
Retrieving from an ArrayList
• 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
Legacy ArrayLists
• Before Java 1.5, ArrayLists were not
parameterized
– ArrayList old = new ArrayList();
• Any object type could be added to any list
• Retrieving returned an Object type, and required
casting
– String a = (String)old.get(0);
• Use the parameterized lists in new code
development
Auto-Boxing
• 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
• 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();
Replacing and Removing an Item
• 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
Arrays: Declaration
• 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
Arrays: Instantiation
• 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();
Arrays: Initialization Syntax
• 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};
Anonymous Array
• 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'} );
Arrays: State
• 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
Array Contents
• Arrays of primitives actually contain the
primitive values
x:
– int[] x = {2, 5, 9};
• Arrays of an object type contain references
2
5
9
– String[] names = {"Joe", "Fred", "Ann"};
names:
ArrayList objects always contain
Object references
--references can be null
Joe
Fred
Ann
Copy an Array
• 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);
Array Copy Glitch
• 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
Partially Filled Arrays
• 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
Partially Filled Arrays
• 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];
Shifting Elements in an Array
• 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
In this case,
copying begins
at index 4
(copied to index
3) and proceeds
left to right
Shifting Elements in an Array
• Slide elements up one position (similar to
– 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
In this case,
copying begins
at index 5
(copied to index
6) and proceeds
right to left
Growing an Array
• 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
method call completes
private String[] names = {};
private int numNames = 0;
if (numNames==names.length){
String[] old = names;
names =
new String[2*names.length+1];
System.arraycopy
(old,0, names,0, numNames);
}
names[numNames++]=newName;
}
ArrayList vs Array
• 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
Searching a List
• 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
Sequential Search in an Array
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
}
Finding a Max in an Array
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;
}
Enhanced for loop
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;
These algorithms could be
return max;
applied to ArrayLists as well
}
Enhanced for loop
• 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;
Parallel Arrays
• 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
330-555-1212
Sally Harmon
330-999-0099
…
…
• Such structures can be
more elegantly
implemented using
objects:
private String name, tele;
…
}
or
contacts;
MultiDimensional Arrays
• Since each element of an
array (often called a row)
can hold an object
reference, it is possible to
refer to another array.
double[][] x = new double[3][4];
x:
rows
– When a row is another
array, its components are
called columns
– This organization gives a 2dimensional feel (rows and
columns) to the outer array
3.5
2.6
-9.1 0.6
0.7
-9.1 2.0
1.1
2.5
0.1
6.4
0.2
columns
System.out.println(x[1][3]);
//displays 1.1
x[0][0] = 1.5;
//changes 3.5 to 1.5
MultiDimensional Arrays
• Each row can be a
different size array
– This is sometimes
called a ragged array
are allowed (to any
depth)
int[][] x = new int[3][];
x:
rows
String[][][][] z = new String[2][3][2][4];
– //try drawing this!!!
2
8
0
0
2
8
7
1
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;
Summary
• 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