Transcript Array Lists - AP Central

```Array Lists
Pat Phillips
Craig High School
Janesville, Wisconsin
2005
1
Objectives





A review of arrays
An introduction to ArrayList class
Method analysis of ArrayList class
Manipulating data in array lists
Lab practice using array lists with
authentic data
2
Arrays – A review

An array is a fixed-length sequence of values
of the same type.
Each value has a numeric index
The entire array
has a single name
0
ages
1
2
16 21 8
3
4
5
6
7
8
9
37 18 11 27 14 17 12
An array of size N is indexed from zero to N-1
This array holds 10 values that are indexed from 0 to 9
3
Arrays – A review

Declare an array before using.
int[] a = new int[5];
This creates an array of integers with a capacity of 5 indexed
from 0 to 4.
char[] code = new code[100];
This creates an array of characters with a capacity of 100
indexed from 0 to 99.
4
Arrays – A review

You access array elements with an integer
index, using subscript notation as in these
assignment statements.
a[0] = 78;
a[1] = 89;
5
Arrays – A review
Input
// filling arrays with consecutive integers
for (count = 0;count < 20;count++)
{
myArray[count] = count ;
}
// filling array from file
int count = 0;
while(count < maxCount && !inFile.eof())
{ int a = inFile.readInt(); // EasyReader
if (!inFile.eof())
{ myArray[count] = a;
count++;
}
}
6
Arrays – A review

Arrays can be instantiated and initialized in
one step with an initializer list.
char myGrades[] = {‘A’,‘C’,‘D’};
7
Arrays – A review

The number of elements an array can hold is
accessed by using the length field of the array
object: someArray.length
for (int x = 0; x < someArray.length ; x++)
{
System.out.print("\t"+ someArray[x]);
}
The length is the number of elements the array
can hold….not the number of positions filled.
8
Arrays – A review

Arrays are often partially filled and you need to
remember the number of elements you actually
placed in the array. This can be accomplished with a
counter.
int count = 0;
boolean done = false;
while(count < maxCount && !done)
{ System.out.println("Enter integer (-1 to quit.): ");
int a = input.readInt(); // EasyReader
if (a != -1)
{ vect[count] = a;
count++;
}
else
done = true;
}
size = count; // Remember number of filled elements
}
9
Arrays – A review

Arrays can hold primitive values or object
references.
String[] names = new String[20];


This declaration reserves space to store 20
references to String objects.
This does not create the String objects;
each object stored must be instantiated
independently.
10
Arrays – A review
original

new
If you run out of
room in an array, you
must declare a larger
array and copy the
elements from the
original array to the
larger array.
free space
11
Arrays – A review

Observe the following code that copies the
data from the original array to the new, larger
array.
int[] newArray = new int[2* original.length];
for (int i = 0; i < original.length; i++)
{
newArray[i] = original[i];
}
original = newArray;
12
Arrays – A review

The System class contains several useful
class fields and methods. One tool that helps
us now is arraycopy.
int[] mewArray = new int[2 + original.length];
System.arraycopy(original, 0, newArray, 0,
original.length);
original = newArray;
13
Arrays – A review

An array can be passed as a parameter to a method in
its entirety.

Because an array is an object, the reference to the array
is passed which makes the formal and actual
parameters aliases of each other.

Because of this, changing any element of the array in
the method will change that element in the original also.

If a single element of an array is passed to a method it
will follow the rules for passing that data type as a
parameter.
14
Arrays – A review

It is not very convenient to track array
sizes and to grow arrays when they run
out of space.

If you are collecting objects, use ArrayList.

If you are collecting numbers, make a choice.
Which is the least inconvenient?

Using wrapper classes and ArrayList?

Tracking array size?
15
Array lists
Definitions
Methods
Code Samples
Class projects
16
Array Lists




The ArrayList class is part of the Java
standard class library.
It provides services similar to arrays.
It is part of the Collections API; a group of
classes to help organize and manage
other objects.
The ArrayList class is implemented
using an array.
17
Array Lists




Unlike arrays, an array list is not declared
to store a particular data type.
It stores data as an array of Object
references.
Because of this, primitives must be first
stored in a wrapper class to be stored in an
array list .
You need to remember the type of objects
stored in an array list to cast them back to
their original type when accessing them.
18
Array Lists

The ArrayList class simplifies many of
the operations routinely used with arrays
such as resizing, inserting and deleting
data, and handling exceptions.
19
Array Lists
From Java API Docs
Samples:
ArrayList musicians = new ArrayList( );
ArrayList newFriends = new ArrayList(oldFriends);
20
ArrayList accounts = new ArrayList(100);
Array Lists
Automatically keeps track of the list capacity
(the length of the allocated array) and list size
(the number of elements currently in the list)
capacity
size
“Sue" “Bob" “Joe"
21
Array Lists
Method Summaries for accessing and adding data
size() Returns the number of elements in this list.
get(int index)
Returns the element at the specified position
in this list.
add(int index, java.lang.Object o)
Inserts the object at the specified position
in this list.
add(java.lang.Object o)
Appends (adds) the object to the end of this
array list.
set(int index, java.lang.Object o)
Replaces the element at the specified position
in this list with the specified object.
22
Array Lists
When data is added at the end of the array
list, the capacity is checked. If it is full it adds
space (doubles) and then adds the new data
reference to the end.
capacity
“Sue" “Bob" “Joe" “Jim"
23
Array Lists
When data is added to a spot within the array
between existing elements, the capacity is
checked. If it is full it adds space (doubles) and
then adds the new data reference to the
prescribed location and moves everything up
one index value. newFriends.add(1, “Jim”);
capacity
“Sue" “Jim " “Bob" “Joe"
New element
24
Array Lists
filling array list using a loop and the Integer wrapper class
for (count = 0;count < 20;count++)
{
thisList.add(new Integer(count));
}
filling array list with input
while(!infile.eof())
{
int a = input.readInt();//using EasyReader
if (!inFile.eof())
{
mylist.add(new Integer(a));
}
}
25
Array Lists
Method Summary for deleting data
remove(int index) Removes the element at the
specified position from this list.
Removes the designated element and moves all others down in index
value to fill in the gap.
newFriends.remove(0);
capacity
“Jim" “Bob " “Joe"
“Sue” removed
26
Array Lists
Additional Method Summaries
isEmpty () Returns a boolean true if list contains
no elements.
clear ()
Removes all elements of the list.
contains (java.lang.Object o)
Returns true if this list contains the specified
object.
indexOf (java.lang.Object o)
Returns the int value of the index of the first
occurrence of the specified object.
toString Class method called whenever an ArrayList
object is sent to the println method.
27
Array Lists
Method Summaries for iterating data
iterator()
Returns an iterator over the
elements in this list (AB only).
listIterator()
Returns a list iterator over
the elements in this list (AB only).
These methods are tested in the AB test only.
They allow for ease in traversing an array list.
28
Array Lists
Additional comments:
 get(i) and set(i) are efficient methods because
they allow for random access to elements in
the array list.
 The ArrayList class throws an
IndexOutOfBoundsException
when i<0 or i  size(). This happens in get(),
set(), remove() and add(int, object).
 Efficiency is a major consideration when
choosing between arrays and array lists.
29
Array Lists
Additional comments:
 Using equals with array lists will use the
default Object equals and will compare
references not contents.
 equals returns true if two ArrayList
references are the same, false otherwise.
30
Array Lists
Array Lists as Parameters to Methods:
 A method cannot change the size of an
array parameter. Why not?
 A method can change the length of an
array list that is passed as a parameter.
Why?
 You can change the contents of the array
list but you cannot change the reference.
31
Find the largest value in array list named nums
Integer large = (Integer)nums.get(0);
for (int i = 0; i < nums.size(); i++)
{ Integer tempLarge=(Integer)nums.get(i);
// Notice the casting of the ListArray
object to type Integer.
if(tempLarge.compareTo(large) > 0)
{ large = tempLarge;
}
}
large.intValue() is the largest int value in the
ArrayList
32
Adding the total of values
int n2;
int total = 0;
for (int i =0; i < nums.size();
i++)
{
Integer n = (Integer)nums.get(i);
total += n.intValue();
}
33
Finding a matching object
..
..
Student studentToFind = student1;
//could be incoming object parameter of a method
for(int i =0; i < school.size(); i++)
{
Student s = (Student)school.get(i);
if (s.equals(studentToFind))return true;
}
return false;
34
Array Lists
Class Activities
 Demonstrate array list creation, access
and manipulation with real objects
before coding.
1.
Use egg cartons to simulate the array capacity.
2.
Cut the carton in half the long way.
3.
Fill the first half with a small candy in each spot.
4.
When adding the 7th candy element double the size of the
array list by placing the second half to the end of the first.
5.
Practice methods of ArrayList manipulating the candies.
6.
Of course, the last method to practice is clear()!
35
Array Lists

Create projects that use authentic data.
1.
Search for data-type information on a topic of choice; sport
stats, population, land use, tourist data of a specific country or
city, transportation data, social demographics . . . . The list is
endless. Online almanacs are a great source of inspiration.
2.
Create a class to define the data objects. Example: the
BowlGame class might have 6 fields – name, city, team1,
team2, score1, score2
3.
Add methods such as toString and accessor and modifier
methods.
(continued)
36
Array Lists
Class Activities
 Create projects that use authentic data.
4. Determine what statistical analysis might be useful and
meaningful to generate. Totals? Averages? Greatest? Least?
Sorts? Median?
5. Create a menu driven program with methods to load the array
list (read from a text file), display data elements, add or delete
information, generate statistics and display various results.
Write the data back to the file.
(Excerpts of an example project are included in these materials.)
37
Array Lists
Summary

Both arrays and array lists create indexed storage of data.

Arrays are most efficient with primitive data.

The ArrayList class offers many methods to simplify creating and
manipulating object data.

The choice between using arrays or array lists is determined by the type
of data to be stored and the operations that must be performed on the
data.

Creating classroom activities that analyze authentic data reinforces the
use of OOD (object-oriented development), teaches valuable statistical
analysis, and efficient data storage and retrieval.
38
```