The List Interface and Arraylist Class Chapter Xiii Topics

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 94

Chapter XIII

The List Interface and ArrayList Class

Chapter XIII Topics

13.1 Introduction
13.2 What is an Interface?
13.3 The Collection Hierarchy
13.4 Java Collection Classes
13.5 ArrayList Methods
13.6 ArrayList and Primitive Data
Types
13.7 ArrayList and Generics
13.8 ArrayList and the Enhanced
For Loop
13.9 Summary

Chapter XIII The List Interface and ArrayList Class 621


13.1 Introduction

Most programming languages have one type


of array. Frequently it is - like the static
array of the previous chapter - both one-
dimensional and multi-dimensional.
Java has two types of arrays. Java has the
static array, shown last chapter, which is
constructed with a fixed size that cannot be
altered during program execution.
Additionally, Java has a dynamic array,
which does not require a predetermined size
at instantiation that can be altered during
program execution. The focus of this
chapter is on the dynamic array, which is
implemented with the ArrayList class. The

622 Exposure Java 2020, APCS Edition 06-06-10


secondary focus is on the introduction of the
List interface.

You will see that the dynamic array is very


different from the static array and an
important goal of this chapter is to clarify
when it is best to use a static array and when
it is better to use a dynamic array.

Java Arrays

 Java has a static array capable of


multi-dimensions.
 Java has a dynamic array capable of
only one dimension.
 The ArrayList class is used for the
dynamic array.

Chapter XIII The List Interface and ArrayList Class 623


13.2 What is an Interface?

Now before we plunge into the details of


working with the dynamic ArrayList class
we need to take a detour and appreciate the
meaning of the word interface. The word
interface certainly gets a lot of press, but it
is a very good word. In the area of
technology you are constantly interfacing.
We think of an interface as a means to
communicate and access the capability of
some object. Just look at a television. In the
old days people were forced to walk up to a
television and manually turn knobs to select
channels and volume. Today we have a
remote control that interfaces with the
television.
Java's interface is not exactly like a
television remote control, but there are
similarities. You may know absolutely

624 Exposure Java 2020, APCS Edition 06-06-10


nothing about the technology required to
create a television remote control. Yet, you
can discuss the functionality of such a
control. You have the ability to state what
you desire in a remote control and you can
also use a remote control once you are
familiar with the functionality of each
button on the interface.

Imagine the following scenario. A


production manager gathers a team of
engineers and wants a remote control
created. This manager wants the remote
control to handle the following features:

Power on/off
Volume lower/higher
Channels up/down
Switch between
TV/VCR
Play/pause/fast-
forward/rewind VCR
Program VCR

Chapter XIII The List Interface and ArrayList Class 625


The manager is not an engineer. The
manager is an administrator who knows
what the company wants to produce and sell.
Administrators leave the concrete
implementations of their abstract ideas to the
engineers.

The creation of the remote control is like the


creation of a new class. It is possible to
discuss the functionality of the class without
any concern about the implementation of the
class. The first step in class design is to
discuss the data that will be stored and the
manner in which the methods of the class
will access and process the data.

You must realize that it is not sufficient to


give somebody a bunch of method names.
You need to provide the method signatures
that indicate the required parameters for
each method along with appropriate
comments to explain the functionality for
each method. Proper comments should
include a method description along with pre-

626 Exposure Java 2020, APCS Edition 06-06-10


conditions and post-conditions of the
methods.

Java has the ability to create an odd-looking


class, called an interface. It is odd-looking
because it shows a bunch of method
headings without any method bodies. This
is the whole point. The interface only
provides abstract information. The interface
is not concerned with implementation.

Java Interface

A Java interface provides a group of


method signatures that will be available
for any client of a class that implements
the interface.

Implementation details of the interface


methods are neither required nor
desired at the interface level.
Chapter XIII The List Interface and ArrayList Class 627
31.3 The Collection Hierarchy

The ArrayList class does not exist by itself.


It is very different from the static array and
ArrayList is part of an important hierarchy
in the Java language. A hierarchy is a
relationship that goes from general to
specific. A hierarchy resembles a pyramid
structure. We speak of the Catholic Church
as a hierarchy. The Pope is at the top of the
Catholic Church, followed by bishops,
priests, deacons and then parishioners. Java
has an important hierarchy, which is called
the Collection Hierarchy.

628 Exposure Java 2020, APCS Edition 06-06-10


To start this Collection discussion properly
we need to understand the relationship of
different data structures and we start with a
very general data structure, which is the
collection. There are few requirements for a
collection. It is a group of objects without
any special requirements for duplicate
elements or element order. The collection
definition lacks excitement and certainly
detail. Keep in mind we are at the top of
this general-to-specific tour of data
structures. We will now move on to
different types of collections. You will find
that none of the next set of data structures
resembles any data structure you know.

Collection

A collection is a group of objects.

Linear Collections

Chapter XIII The List Interface and ArrayList Class 629


Linear collections are the most common
type of collections and the majority of data
structures you will use in computer science
fall in the linear category. A linear
collection stores its elements in a specific
order. It is possible to identify the position
by some index value or by proximity to the
end of the structure. Linear collections can
have duplicate elements.

Linear Collections

A linear collection stores its elements


in a specific order.
Linear collections can have duplicate
elements.

Lists

A list is a linear collection that allows access


to any element in the list. Access to these
elements may be possible with an index
operator, such as a Java static array or it may

630 Exposure Java 2020, APCS Edition 06-06-10


be with some special accessing method like
Java's ArrayList class. Examples of lists
are static arrays, dynamic arrays, strings,
files, and linked lists.

Lists

A list is a linear collection that allows


access to any element in the list.

Examples of list data structures are


static arrays, dynamic arrays, strings,
files and linked lists.

Stacks and Queues

What type of data structures are stacks and


queues? It was stated earlier that a linear
collection has ordered elements and such is
the case with stacks and queues. On the
other hand, we cannot continue and state
that stacks and queues are lists, because it is
Chapter XIII The List Interface and ArrayList Class 631
not possible to access any element directly
with an index operator or accessing method.
Access to stacks and queues is limited to one
end of the data structure.

Stacks and Queues

Stacks and Queues are linear


collections with element access limited
to the end of the data structure.

Unordered Collections

This type of data structure may seem strange


to you. An unordered collection stores its
elements without concern about any type of
order. Does such a data structure seem odd?
Does this happen in real life? Consider the
following situation. You, as a student, are a
single element in a school. What type of
structure is the school. I would claim that
most of the time the school is a linear
collection. I am using "most of the time"

632 Exposure Java 2020, APCS Edition 06-06-10


because when you are in class there is a
definite class location that you occupy
during every period of the school day. If we
also add the fact that teachers have a seating
chart, I could argue that every student in a
school can be accessed. Certainly the
administration would be upset if they cannot
find a student. The story changes between
classes. The students are still part of the
school, but they are no longer in any
noticeable order or location. Students are
somewhere in the school. The same is true
during a pep rally. The students are present
in the gym, and students may be seated in a
Sophomore, Junior or Senior section.
However, they are sitting in their own
section without regard for any order or
location.

Unordered Collections

An unordered collection stores


elements without order.

Chapter XIII The List Interface and ArrayList Class 633


Bags

A bag is an unordered collection that can


have duplicate elements. Consider a bag of
coins. The bag can contain pennies, nickels,
dimes and quarters and it can contain
multiple quarters or any other type of coin.
At the same time the coins are not ordered in
any type of pattern. .

Bags

A bag is an unordered collection that


can have duplicate elements.

Sets

634 Exposure Java 2020, APCS Edition 06-06-10


A set is an unordered collection that cannot
have duplicate elements. The school
example given earlier at the pep rally
demonstrates a set of Sophomore students, a
set of Junior students and a set of Senior
students. It is set of students and not a bag
of students, because there are no duplicates.

The set data structure follows the


mathematical rules of sets. Sets have
members, subsets and supersets. There are
set intersections, set unions and set
differences that are possible set operations.
These operations exist in mathematical logic
and also in a programming language that
supports the set data structure.

Java does have a set data structure. Does


this mean that Java is one of the few
languages with this capability? Java and
Pascal are some of the few languages, which
provide a set data structure. At the same
time you can create your own set data
structure with some existing data structure,
like an array.
Chapter XIII The List Interface and ArrayList Class 635
Sets

A set is an unordered collection without


any duplicate elements.

31.4 Java Collection Classes

The collection data structure and many of


their offspring are well represented in Java.
Java starts with a Collection interface,

636 Exposure Java 2020, APCS Edition 06-06-10


which is the root interface of the collection
hierarchy. The Collection interface
continues with two subinterfaces, which are
the List and the Set. The List interface is
implemented by the ArrayList and
LinkedList classes. The Set interface is
implemented by the HashSet and the
TreeSet classes. Figure 13.1 shows the
relationship between these interfaces and
classes.

Figure 13.1
Collection
interface

List Set
interface interface

ArrayList LinkedList HashSet TreeSet


class class class class

Chapter XIII The List Interface and ArrayList Class 637


I need to reinforce the concept that an
interface only has abstract methods. These
abstract methods provide the signatures of
the methods and nothing more. The
interface depends on some concrete class to
implement its methods. This means that it is
not possible to instantiate some object with
an interface.

Program Java1301.java, in figure 13.2,


proves that point by using Java's Collection
interface to construct a collect object. After
the object is supposedly constructed the
contents of the object are displayed.

638 Exposure Java 2020, APCS Edition 06-06-10


Figure 13.2
// Java1301.java
// This program demonstrates that you
cannot work with an abstract <interface>
// directly. The <Collection> interface is at
the top of the Java built-in
// data structures hierarchy.

import java.util.*;

public class Java3101


{
public static void main(String args[])
{

System.out.println("\nJAVA1301.JAVA\n");
Collection collect = new Collection();
System.out.println("Collection contains: "
+ collect);
}
}

Chapter XIII The List Interface and ArrayList Class 639


Java1301.java Output

Java1301.java:15:
java.util.Collection is
abstract; cannot be
instantiated
Collection
collect = new Collection();

^
1 error

Java is not happy with my attempt at


constructing an object with the Collection
interface. We are notified with a stern
compile error message that we are quite
confused. Do you suspect that it makes any
difference with a subinterface? Both List
and Set are subinterfaces of the Collection
interface. Can you instantiate any objects
with subinterfaces?

640 Exposure Java 2020, APCS Edition 06-06-10


Program Java1302.java, in figure 13.3, is
very similar to the previous program. This
time we try to construct a List object and a
Set object. You will note in the output that
we are now rewarded with two error
messages.

On a side note, if I did not mention it before,


it is quite common to give an object the
same identifier as a class with a lower-case
letter. To some people this is very
confusing and to others it is very convenient
because it instantly identifies the object with
its class.

Figure 13.2
// Java1302.java
// This program generates the same
Chapter XIII The List Interface and ArrayList Class 641
compile error message as the previous
program.
// <List> and <Set> are interfaces and
cannot be instantiated.
// <List> and <Set> are sometimes called
"subinterfaces."

import java.util.*;

public class Java1302


{
public static void main(String args[])
{

System.out.println("\nJAVA1302.JAVA\n");
List list = new List();
Set set = new Set();
System.out.println("list contains: " + list);

System.out.println("set contains: " +


set);
}
}

642 Exposure Java 2020, APCS Edition 06-06-10


Java1302.java Output

Java1302.java:15:
java.util.List is abstract;
cannot be instantiated
List list =
new List();
^
Java1302.java:16:
java.util.Set is abstract;
cannot be instantiated
Set set = new
Set();

The time has come to create some objects


without Java compile error messages
blocking your goals. Program
Java1303.java, in figure 13.4, goes one
more step down the Collection hierarchy
and introduces the ArrayList, LinkedList,
Chapter XIII The List Interface and ArrayList Class 643
HashSet and TreeSet classes. Each one of
these classes implements the methods that
started as abstracts methods in the
Collection interface. The example in figure
13.4 does not yet demonstrate any method
implementations, but it does construct four
objects for each one of the four classes.

The output of the four classes displays an


empty set of square brackets. Square
brackets are normal for Collection classes
and they are empty, because there are no
values yet that have been added to any of the
objects.

Figure 13.4
// Java1303.java
// This program demonstrates the four
<Collection> classes.

644 Exposure Java 2020, APCS Edition 06-06-10


// The contents of each object can be
viewed using <println>.
// This program only displays a set of empty
[ ] brackets,
// because no value have been added to
any one of the objects.

import java.util.*;

public class Java1303


{
public static void main(String args[])
{

System.out.println("\nJAVA1303.JAVA\n");
ArrayList object1 = new ArrayList();
LinkedList object2 = new LinkedList();
HashSet object3 = new HashSet();
TreeSet object4 = new TreeSet();

System.out.println("object1 contains " +


object1);
System.out.println("object2 contains " +

Chapter XIII The List Interface and ArrayList Class 645


object2);
System.out.println("object3 contains " +
object3);
System.out.println("object4 contains " +
object4);
System.out.println();
}
}

Java1303.java Output

JAVA1303.JAVA

object1 contains []
object2 contains []
object3 contains []
object4 contains []

Program Java1304.java, in figure 13.5,


instantiates the same objects as the previous
program. The only difference is that on the
646 Exposure Java 2020, APCS Edition 06-06-10
left side of the declaration statement you
will see the Collection interface name and
not the name of each class that is being
instantiated. This type of syntax is not only
allowed, it is actually very desirable. You
can always use this sort of approach with
either a super class or an interface. The
benefits of this type of declaration will be
explained in a future chapter.

Figure 13.5
// Java1304.java
// This program is almost identical to the
previous program.
// The same four objects are instantiated
with each of the four
// <Collection> classes. This time note that
the class on the
// left side of the object actually is the
Chapter XIII The List Interface and ArrayList Class 647
<Collection> interface.
// This is not only allowed, but frequently
very desirable for
// proper class interaction.

import java.util.*;

public class Java1304


{
public static void main(String args[])
{

System.out.println("\nJAVA1304.JAVA\n");
Collection object1 = new ArrayList();
Collection object2 = new LinkedList();
Collection object3 = new HashSet();
Collection object4 = new TreeSet();

System.out.println("object1 contains " +


object1);
System.out.println("object2 contains " +
object2);
System.out.println("object3 contains " +

648 Exposure Java 2020, APCS Edition 06-06-10


object3);
System.out.println("object4 contains " +
object4);
System.out.println();
}
}

Java1304.java Output

JAVA1304.JAVA

object1 contains []
object2 contains []
object3 contains []
object4 contains []

Empty brackets are a boring output, which is


not to say that most outputs in this book
have been very exciting. Much in life is
relative and program execution output
displays is one of life's relative examples.
On to program Java1305.java, in figure
Chapter XIII The List Interface and ArrayList Class 649
13.6, which creates four objects and then
adds the same ten values to each object.

This program introduces the add method of


the Collection interface. As you observe the
next series of program examples, pay close
attention to the add method. You will find
that the identifier is the same three-letter
add, but its behavior will alter with different
objects.

Figure 13.6
// Java1305.java
// This program demonstrates the <add>
method of the <Collection> interface.
// The <add> method is implemented in
each one of the four <Collection>
// classes. This program may give the
impression that the <add> method
// is identical in each one of the four
classes.

650 Exposure Java 2020, APCS Edition 06-06-10


import java.util.*;

public class Java1305


{
public static void main(String args[])
{

System.out.println("\nJAVA1305.JAVA\n");
Collection object1 = new ArrayList();
Collection object2 = new LinkedList();
Collection object3 = new HashSet();
Collection object4 = new TreeSet();

for (int k = 1; k <= 10; k++)


{
Integer intObj = new Integer(k);
object1.add(intObj);
object2.add(intObj);
object3.add(intObj);
object4.add(intObj);
}

System.out.println("object1 contains " +

Chapter XIII The List Interface and ArrayList Class 651


object1);
System.out.println("object2 contains " +
object2);
System.out.println("object3 contains " +
object3);
System.out.println("object4 contains " +
object4);
System.out.println();
}
}

Java1305.java Output

JAVA1305.JAVA

object1 contains [1, 2, 3, 4,


5, 6, 7, 8, 9, 10]
object2 contains [1, 2, 3, 4,
5, 6, 7, 8, 9, 10]
object3 contains [1, 2, 3, 4,
5, 6, 7, 8, 9, 10]
object4 contains [1, 2, 3, 4,
5, 6, 7, 8, 9, 10]

652 Exposure Java 2020, APCS Edition 06-06-10


The next program example is quite simple,
but it is very significant. It demonstrates
something both about the nature of each one
of the Collection classes and it also tells you
something significant about the add method.
Program Java1306.java, in figure 13.7,
starts with the construction of four objects,
just like the previous two programs. The
execution continues with a loop that iterates
ten times and a random number is added to
each one of the objects. The random
numbers are selected intentionally in such a
manner that there will be duplicate numbers.

Figure 13.7
// Java1306.java
// This program demonstrates that <List>
classes can store duplicate
// elements, but <set> classes do not store
duplicate elements.

import java.util.*;
Chapter XIII The List Interface and ArrayList Class 653
public class Java1306
{
public static void main(String args[])
{

System.out.println("\nJAVA1306.JAVA\n");
Collection object1 = new ArrayList();
Collection object2 = new LinkedList();
Collection object3 = new HashSet();
Collection object4 = new TreeSet();

Random rand = new Random(500);


for (int k = 1; k <= 10; k++)
{
int rndInt = rand.nextInt(10) + 100;
Integer intObj = new Integer(rndInt);
object1.add(intObj);
object2.add(intObj);
object3.add(intObj);
object4.add(intObj);
}

System.out.println("object1 contains " +

654 Exposure Java 2020, APCS Edition 06-06-10


object1);
System.out.println("object2 contains " +
object2);
System.out.println("object3 contains " +
object3);
System.out.println("object4 contains " +
object4);
System.out.println();
}
}

Java1306.java Output

JAVA1306.JAVA

object1 contains [105, 104,


102, 102, 105, 105, 106, 108,
107, 102]
object2 contains [105, 104,
102, 102, 105, 105, 106, 108,
107, 102]
object3 contains [108, 107,
106, 105, 104, 102]
object4 contains [102, 104,
105, 106, 107, 108]
Chapter XIII The List Interface and ArrayList Class 655
The output display cannot verify this but
each object starts with zero elements and
grows dynamically in storage size as
elements are added. However, we can make
some interesting observations about the
output display. Objects object1 and object2
store a random set of integers, which include
duplicate elements. Objects object3 and
object4 have no duplicate elements. The
same method identifier add is used for four
objects, but the implementation of method
add is not the same for the four objects.
ArrayList and LinkedList objects are List
data structure and store duplicate elements.
HashSet and TreeSet objects are Set data
structures and cannot store duplicate
elements.

13.5 ArrayList Methods

656 Exposure Java 2020, APCS Edition 06-06-10


Java has an answer to the static array
shortcomings. It is the ArrayList class. In
the last section the ArrayList class was
introduced as one of the four Collection
classes. Remember how the Collection
interface splits into the two subinterfaces Set
and List. ArrayList is one of the classes
that implements the List interface. In this
section the focus is on the primary methods
used with the ArrayList class. Note that
these methods are also tested on the AP
Computer Science Exam.

With an ArrayList object the quantity of


elements can be altered on the fly during
program execution, which is officially
known as dynamic resizing. Dynamic
resizing it great, but there are other features
available. Static arrays have a conspicuous
absence of methods to enhance the data
processing needs. The ArrayList class not
only handles resizing, but it also has a
convenient set of methods to manipulate
data. Program Java1307.java, in figure
13.8, demonstrates how to construct an
Chapter XIII The List Interface and ArrayList Class 657
ArrayList object and it shows how to use
the add method to add new elements to the
array. Note how new elements are added to
the end of the ArrayList object.

Figure 13.8
// Java1307.java
// This program demonstrates the <add>
method of the <ArrayList> class.
// Note that each name is added to the
end of the list.

import java.util.ArrayList;

public class Java1307


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1307.java\n");

658 Exposure Java 2020, APCS Edition 06-06-10


ArrayList names = new ArrayList();
names.add("Isolde");
names.add("John");
names.add("Greg");
names.add("Maria");
names.add("Heidi");

System.out.println("names contains "


+ names);
System.out.println();
}
}

Figure 13.8 Continued


Java1307.java Output

Java1307.java

names contains [Isolde, John,


Greg, Maria, Heidi]

Chapter XIII The List Interface and ArrayList Class 659


ArrayList Method add

names.add("Tom");

The add method allocates space for the


newly enlarged array and then stores
the new array element at the end of the
ArrayList object.

You should have observed a feature of the


ArrayList class that does not exist with
Java static arrays. All the elements in the
array are displayed rather casually with the
use of a simple statement like
System.out.println(names); This is a
serious nono with a static array. Actually, it
is not a nono in the compile sense. The
result is not real practical. All you get is

660 Exposure Java 2020, APCS Edition 06-06-10


some memory address of the array storage
location.

Displaying ArrayList Elements

ArrayList elements can be accessed


with various methods. It is possible to
display all the elements inside square
brackets, separated by commas by
using the println method.

System.out.println(names);

[Isolde, John, Greg, Maria,


Heidi]

Java static arrays use the length field to


store the number of elements in an array
object. A static array can use a field,
because it can be made final and access is
Chapter XIII The List Interface and ArrayList Class 661
possible without the possibility of altering
the field value. A dynamic array, like
ArrayList uses a method, which alters a
private field value. Program
Java1308.java, in figure 13.9, demonstrates
the use of the size method.

Figure 13.9
// Java1308.java
// This program uses the <size> method
to determine the number of elements
// in an <ArrayList> object.
// Note that the value return by the
<size> method changes when more
names
// are added to the <ArrayList> object.

import java.util.ArrayList;

public class Java1308


{

662 Exposure Java 2020, APCS Edition 06-06-10


public static void main(String args[])
{
System.out.println();

System.out.println("Java1308.java\n");

ArrayList names = new ArrayList();


names.add("Isolde");
names.add("John");
names.add("Greg");
System.out.println("names contains "
+ names);;
System.out.println("There are " +
names.size() + " elements in the names
object.");

names.add("Maria");
names.add("Heidi");
System.out.println("names contains "
+ names);
System.out.println("There are " +
names.size() + " elements in the names
object.");
System.out.println();
}

Chapter XIII The List Interface and ArrayList Class 663


}

Java1308.java Output

Java1308.java

names contains [Isolde, John,


Greg]
There are 3 elements in the
names object.
names contains [Isolde, John,
Greg, Maria, Heidi]
There are 5 elements in the
names object.

ArrayList Method size

664 Exposure Java 2020, APCS Edition 06-06-10


int count = names.size();

The size method returns the number of


elements of the ArrayList object
names.

Program Java1309.java, in figure 13.10,


shows how individual elements of the
names object are accessed with the get
method. Note how the size method controls
the loop. Any attempt to access an array
element at a location that does not exist,
results in an
IndexOutOfBoundsException error
message, which is precisely what happens
with static arrays.

Figure 13.10
// Java1309.java
Chapter XIII The List Interface and ArrayList Class 665
// This program shows how to access
specified elements in an <ArrayList>
object
// with the <get> method.

import java.util.ArrayList;

public class Java1309


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1309.java\n");

ArrayList names = new ArrayList();


names.add("Isolde");
names.add("John");
names.add("Greg");
names.add("Maria");
names.add("Heidi");

System.out.println();

666 Exposure Java 2020, APCS Edition 06-06-10


for (int k = 0; k < names.size(); k++)
System.out.println(names.get(k));

System.out.println();

for (int k = names.size()-1; k >= 0; k--


)
System.out.println(names.get(k));

System.out.println();
}
}

Figure 13.10 Continued


Java1309.java Output

Java1309.java

Isolde
John
Greg
Maria
Chapter XIII The List Interface and ArrayList Class 667
Heidi

Heidi
Maria
Greg
John
Isolde

ArrayList Method get

System.out.println(names.get(3));

The get method accesses a specified


array element. The parameter of the
get method is the index of the ArrayList
object and starts at 0.

Any attempt to access an element at a


non-existing index results in an
IndexOutOfBoundsException error.

668 Exposure Java 2020, APCS Edition 06-06-10


The static array index operator is very
versatile. It can be used to access array
elements for display and it can also be used
to change the value of an array element.
ArrayList methods are more specialized.
The get method is fine for displaying and
assigning individual elements, but another
method is required to alter any values. This
job is performed by the set method. Method
set requires two parameters, one for the
array element index and a second parameter
for the new array element value. Program
Java1310.java, in figure 13.11, starts with
five initial names and then changes four of
the names.

Figure 13.11
// Java1310.java
// This program demonstrates the <set>
method of the <ArrayList> class, which
Chapter XIII The List Interface and ArrayList Class 669
// replaces existing elements with a new
object.

import java.util.ArrayList;

public class Java1311


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1310.java\n");

ArrayList names = new ArrayList();


names.add("Isolde");
names.add("John");
names.add("Greg");
names.add("Maria");
names.add("Heidi");

System.out.println("names contains "


+ names);
System.out.println();

670 Exposure Java 2020, APCS Edition 06-06-10


names.set(1,"Jessica");
names.set(2,"Anthony");
names.set(3,"Haley");
names.set(4,"Alec");

System.out.println("names contains "


+ names);
System.out.println();
}
}

Java1310.java Output

Java1310.java

names contains [Isolde, John,


Greg, Maria, Heidi]

names contains [Isolde,


Jessica, Anthony, Haley, Alec]

Chapter XIII The List Interface and ArrayList Class 671


ArrayList Method set

names.set(4,"Tom");

The set method uses the first parameter


as the index location to find an array
element and then replaces it with the
value of the second set parameter. You
will get an error if you try to access an
index location, which has not been
allocated yet.

Earlier in this chapter, ArrayList was


advertised as a dynamic array. Dynamic in
the sense that resizing is possible during
program execution. You have seen objects
grow in size by adding additional elements.
Resizing also can be used to make an array
data structure smaller. Program
Java1311.java, in figure 13.12, resizes the
array with the remove method. Method
remove requires a single parameter, which
is the index of the array element to be
removed.

672 Exposure Java 2020, APCS Edition 06-06-10


Figure 13.12
// Java1311.java
// This program demonstrates the
<remove> method of the <ArrayList>
class to
// delete a specified list element.

import java.util.ArrayList;

public class Java1311


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1311.java\n");
ArrayList names = new ArrayList();
names.add("Isolde");
names.add("John");
names.add("Greg");
names.add("Maria");
names.add("Heidi");
System.out.println("names contains
Chapter XIII The List Interface and ArrayList Class 673
" + names);
System.out.println();
names.remove(2);
System.out.println("names contains "
+ names);
System.out.println();
names.remove(3);
System.out.println("names contains "
+ names);
System.out.println();
}
}

Java1311.java Output

Java1311.java

names contains [Isolde, John,


Greg, Maria, Heidi]

names contains [Isolde, John,


Maria, Heidi]

names contains [Isolde, John,


Maria]

674 Exposure Java 2020, APCS Edition 06-06-10


ArrayList Method remove

names.remove(3);

The remove method removes the array


element at the index location of its
parameter and decreases the object
size by one array element.

You will get an error if you try to access


an index location, which does not exist.

Chapter XIII The List Interface and ArrayList Class 675


The add method is overloaded. An earlier
program example introduced the add
method with a single parameter. This single
parameter provides the value of a new array
element, which is added as the last element
of the array. It is also possible to add a new
element at a specified location. Be careful
and do not confuse this second add method
with the set method. Method set alters the
value at a specified index. The overloaded
add method inserts a new array element at a
specified index and in the process bumps
elements to the next index value. Program
Java1312.java, in figure 13.13, will appear
similar to the previous set program example.
The key difference is that this time the array
grows in size and none of the original values
are lost.

Figure 13.13
// Java1312.java
// This program demonstrates how to
use the <add> method of the
<ArrayList> class to

676 Exposure Java 2020, APCS Edition 06-06-10


// insert new elements at a specified
location.

import java.util.ArrayList;

public class Java1312


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1312.java\n");

ArrayList names = new ArrayList();


names.add("Isolde");
names.add("John");
names.add("Greg");
names.add("Maria");
names.add("Heidi");

System.out.println("names contains "


+ names);
System.out.println();

Chapter XIII The List Interface and ArrayList Class 677


names.add(2,"Jessica");

System.out.println("names contains "


+ names);
System.out.println();

names.add(3,"Anthony");

System.out.println("names contains "


+ names);
System.out.println();
}
}

Figure 13.13 Continued


Java1312.java Output

Java1312.java

names contains [Isolde, John,


Greg, Maria, Heidi]

names contains [Isolde, John,


Jessica, Greg, Maria, Heidi]

678 Exposure Java 2020, APCS Edition 06-06-10


names contains [Isolde, John,
Jessica, Anthony, Greg, Maria,
Heidi]

ArrayList Method add (second


overloaded add)

names.add(3,"Kathy");

The overloaded add(3,"Kathy") method


adds or rather inserts a new array
element at the indicated index.

There are more methods in the ArrayList


class. The six methods in this section are
AP tested methods, because they are the
most common methods and allow a wide
range of data processing with a dynamic
array.

Chapter XIII The List Interface and ArrayList Class 679


It may seem that the ArrayList, with all its
methods and dynamic resizing, is so
superior to the static array that there exists
little justification to hang on to a type of
array that goes back to the early days of
programming.

The simple reality is that ArrayList, good


and flexible as it may be, is a one-
dimensional array. There exists plenty of
processing that calls for two or more
dimensional processing in the real
computing word.

AP Computer Science Exam Alert

The List interface is tested on the AP


exam. The following six methods will be
tested.

680 Exposure Java 2020, APCS Edition 06-06-10


int size()
boolean add(E obj)
void add(int index, E obj)
E get(int index)
E set(int index, E obj)
E remove(int index)

In the method headings above E is the


data type of the Element that is added
or returned.

The ArrayList class is also tested on


the AP exam and will be tested as
implementing the six methods of the
List interface.

The story of interfaces and implementations


is hardly complete. The primary focus of
this chapter has been on the dynamic array,
following the introduction of the static array.
The ArrayList class is part of a hierarchy
Chapter XIII The List Interface and ArrayList Class 681
that was briefly mentioned to make you
understand where ArrayList fits in the Java
programming language.

What is not yet explained is the manner of


actually implementing an interface. You did
see that ArrayList implements the List
interface, but how this is accomplished was
neither detailed nor even partially explained.
The topic of interfaces and implementations
will be continued in a future chapter.

13.6 ArrayList and Primitive Data


Types

682 Exposure Java 2020, APCS Edition 06-06-10


In the Chapter VI the Integer class was
introduced. The Integer class is a wrapper
class, which stores int values in an object.
This is very important for data structures
that can only store object values. The static
array is quite relaxed about such issues and
can store both primitive types and objects.
The Collection classes, like ArrayList only
store objects.

This does not mean that primitive types are


off limits to an ArrayList object. Courtesy
of the Integer class program
Java1313.java, in figure 13.14, does a fine
job storing int values. A "commented-out"
segment proves that Integer objects are not
int values and cannot be treated as such, like
trying arithmetic addition.

Figure 13.14
// Java1313.java
// This program demonstrates that <int>
values stored into an <ArrayList> object
// must first be converted to <Integer>
objects.
Chapter XIII The List Interface and ArrayList Class 683
// <ArrayList> can only store objects
members, not primitive data types.
// Initially, this program compiles, and
executes. If you remove the comments
// from the program an attempt is made
to add the values of the <numbers>
// object, which is not possible.

import java.util.ArrayList;
import java.util.Random;

public class Java1313


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1313.java\n");
Random rand = new
Random(12345);
ArrayList numbers = new ArrayList();

for (int k = 1; k <= 48; k++)

684 Exposure Java 2020, APCS Edition 06-06-10


{
int rndInt = (rand.nextInt(900) +
100);
numbers.add(new Integer(rndInt));
}

// int sum = 0;
// for (int k = 0; k < numbers.size(); k++)
// {
// sum += numbers.get(k);
// }
// System.out.println("Sum: " + sum);
System.out.println();
}
}

1313.java Output

Java1313.java

The same approach can be used for other


primitive data types, such as double and
boolean. These primitive types both have

Chapter XIII The List Interface and ArrayList Class 685


wrapper classes Double and Boolean, which
can be used to store simple data types as
objects in the ArrayList class.

ArrayList and Primitive Data Types

The ArrayList class can only store


object values.

Primitive data type values can be stored


indirectly using wrapper classes.

The Integer class wraps int values.


The Double class wraps double values.
The Boolean class wraps boolean
values.

686 Exposure Java 2020, APCS Edition 06-06-10


13.7 ArrayList and Generics

Java version 5.0 solved some problems with


Java classes. Prior to Java 5.0 there was a
problem with handling objects. An object
stores a reference, which is a memory
address. Now at this memory address actual
practical data information can be stored of
any type. However, this information can be
any type and that can cause confusion and
peculiarities.

Consider program Java1314.java, in figure


13.15. This program shows an ArrayList
object which properly stores Person objects
as its elements. Two Person objects are
instantiated and then added to the people
object. When an attempt is made to access
individual people objects the program
complains and causes syntax errors. The
error message indicates incompatible types.
This may seem to be a mystery, because
only Person objects are used and how can
they be incompatible? The problem is that
Chapter XIII The List Interface and ArrayList Class 687
the actual value stored for each people
object is a reference and its data type is
unknown.

Figure 13.15
// Java1314.java
// This program has no output, which
does not matter, because it does not
compile.
// You will see two "imcompatible types"
syntax errors. This may seem strange
// because the <ArrayList> object stores
<Person> objects.

import java.util.ArrayList;

public class Java1314


{
public static void main(String args[])
{
System.out.println();

688 Exposure Java 2020, APCS Edition 06-06-10


System.out.println("Java1314.java\n");

ArrayList people = new ArrayList();


people.add(new Person("Joe",21));
people.add(new Person("Sue",20));

Person student1 = people.get(0);


Person student2 = people.get(1);
System.out.println();
}
}

class Person
{
private String name;
private int age;

public Person (String n, int a)


{
name = n;
age = a;
}
}

Chapter XIII The List Interface and ArrayList Class 689


Java1314.java Output

C:\Users\leonschram\Desktop\AP
CSChapters2009\ChapterProgsAPC
S\Progs13\Backup\Java1314.java
:21: incompatible types
found : java.lang.Object
required: Person
Person student1 =
people.get(0);

^
C:\Users\leonschram\Desktop\AP
CSChapters2009\ChapterProgsAPC
S\Progs13\Backup\Java1314.java
:22: incompatible types
found : java.lang.Object
required: Person
Person student2 =
people.get(1);

^
Note:
C:\Users\leonschram\Desktop\AP
CSChapters2009\ChapterProgsAPC

690 Exposure Java 2020, APCS Edition 06-06-10


S\Progs13\Backup\Java1314.java
uses unchecked or unsafe
operations.
Note: Recompile with -
Xlint:unchecked for details.
2 errors

Prior to Java 5.0 there was, and still is, a


solution to the unknown data type problem.
Program Java1315.java, in figure 13.16, is
almost identical to the previous program, but
two very strategic castings are used. In each
assignment statement, like Person student1
= (Person) people.get(0); the casting of
the object to (Person) provides Java with
the required information. The program
compiles, executes properly and everybody
is happy.

Figure 13.16
// Java1315.java
// This program compiles and there is

Chapter XIII The List Interface and ArrayList Class 691


still no output. Output is not the
// issue. Understanding the correct
syntax involved does matter.
// In this case lines 22 and 23 cast to the
<Person> class, which makes
// Java happy. Without casting the data
types are unknown.

import java.util.ArrayList;

public class Java1315


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1315.java\n");

ArrayList people = new ArrayList();


people.add(new Person("Joe",21));
people.add(new Person("Sue",20));

Person student1 = (Person)

692 Exposure Java 2020, APCS Edition 06-06-10


people.get(0);
Person student2 = (Person)
people.get(1);
System.out.println();
}
}

class Person
{
private String name;
private int age;

public Person (String n, int a)


{
name = n;
age = a;
}
}

Figure 13.16 Continued


Java1315.java Output

Chapter XIII The List Interface and ArrayList Class 693


Java1315.java

Along comes Java 5.0 and now Java has a


better solution, which is known as generics.
The selection of this term will make more
sense in a later chapter. At the instantiation
of a new ArrayList object the data type to
be stored is specified. Look at
Java1316.java, in figure 13.17, and you
will see the following statement:

ArrayList<Person> people = new


ArrayList<Person>();

This statement tells Java that the new people


object will only store objects of the Person
class. Casting is no longer necessary. This
approach also creates an excellent self-
documenting appearance where the code
makes it clear what is stored in the new
array.

694 Exposure Java 2020, APCS Edition 06-06-10


Figure 13.17
// Java1316.java
// Since Java Version 5.0 the "casting"
solution of the last program is so
// "old Java version". It is now possible
to specify - at the time that the
// <ArrayList> object is constructed -
what kind of object is stored.
// This is called "generics" and in this
case Java knows it is <Person>.

import java.util.ArrayList;

public class Java1316


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1315.java\n");

ArrayList<Person> people = new


Chapter XIII The List Interface and ArrayList Class 695
ArrayList<Person>();
people.add(new Person("Joe",21));
people.add(new Person("Sue",20));

Person student1 = people.get(0);


Person student2 = people.get(1);
System.out.println();
}
}

class Person
{
private String name;
private int age;

public Person (String n, int a)


{
name = n;
age = a;
}
}

696 Exposure Java 2020, APCS Edition 06-06-10


Figure 13.17 Continued
Java1316.java Output

Java1316.java

Program Java1317.java, in figure 13.18,


shows how nicely a Java program works
with the generic feature. You now see a
program, which starts with a number1
object. This object is instantiated to store
Integer objects and three numbers are stored
in numbers1.

A second ArrayList object, numbers2, is


instantiated with the same intention to store
int values wrapped inside Integer objects.
This is followed by accessing three elements
from numbers1 and assigning all three to
numbers2. This works flawlessly without a
hitch.

Figure 13.18
// Java1317.java
// This program shows another benefit of
using generics.
Chapter XIII The List Interface and ArrayList Class 697
// There are two <ArrayList> objects and
both are constructed
// to store <Integer> values. After three
values are entered
// in the <numbers1> object, those
values are then assigned
// to <numbers2>, which works without
problems.

import java.util.ArrayList;

public class Java1317


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1317.java\n");

ArrayList<Integer> numbers1 = new


ArrayList<Integer>();
numbers1.add(new Integer(100));
numbers1.add(new Integer(200));

698 Exposure Java 2020, APCS Edition 06-06-10


numbers1.add(new Integer(300));
System.out.println(numbers1);

ArrayList<Integer> numbers2 = new


ArrayList<Integer>();
numbers2.add(numbers1.get(0));
numbers2.add(numbers1.get(1));
numbers2.add(numbers1.get(2));
System.out.println(numbers2);

System.out.println();
}
}

Java1317.java Output

Java1317.java

[100, 200, 300]


[100, 200, 300]

Chapter XIII The List Interface and ArrayList Class 699


It was mentioned earlier that an array by
definition is a data structure with elements
of the same type. Consider what happens
when generics are not used. Program
Java1318.java, in figure 13.19, adds a
Double object and an Integer object and
finally a String object in the array. Java
allows this practice and the resulting
structure is hardly a proper array.

Figure 13.19
// Java1318.java
// Generics make sure that an array is in
fact an array. An array
// is supposed to be a data structure with
elements of the same type.
// This program example - which does
not use generics - allows the
// list array to store three different data
types.

700 Exposure Java 2020, APCS Edition 06-06-10


import java.util.ArrayList;

public class Java1318


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1318.java\n");

ArrayList list = new ArrayList();


list.add(new Double(3.14159));
list.add(new Integer(200));
list.add(new String("Dubrovnik"));
System.out.println(list);
System.out.println();
}
}

Java1318.java Output

Chapter XIII The List Interface and ArrayList Class 701


Java1318.java

[3.14159, 200, Dubrovnik]

Program Java1319.java, in figure 13.20,


uses the proper approach to instantiating an
ArrayList object. Like before, an attempt is
made to enter three different values into the
array. Java is not amused and rewards the
confused programmer with two error
messages.

Figure 13.20
// Java1319.java
// Once generics are used, Java
becomes very picky. If you want to
create
// an <ArrayList> object to store
<Double> values, such as is shown
below,
// then only <Double> values must be
added.

702 Exposure Java 2020, APCS Edition 06-06-10


// The attempt to add one <Double>,
one <Integer> and one <String> object
// results in two errors.

import java.util.ArrayList;

public class Java1319


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1318.java\n");

ArrayList<Double> list = new


ArrayList<Double>();
list.add(new Double(3.14159));
list.add(new Integer(200));
list.add(new String("Dubrovnik"));
System.out.println(list);
System.out.println();
}
}

Chapter XIII The List Interface and ArrayList Class 703


Figure 13.20 Continued
Java1319.java Output

C:\Users\leonschram\Desktop\Pr
ogs132009\Progs13\Backup\Java1
319.java:21: cannot find
symbol
symbol : method
add(java.lang.Integer)
location: class
java.util.ArrayList<java.lang.
Double>
list.add(new
Integer(200));
^
C:\Users\leonschram\Desktop\Pr
ogs132009\Progs13\Backup\Java1
319.java:22: cannot find
symbol
symbol : method
add(java.lang.String)
location: class
java.util.ArrayList<java.lang.
Double>

704 Exposure Java 2020, APCS Edition 06-06-10


list.add(new
String("Dubrovnik"));
^
2 errors

13.8 ArrayList & the Enhanced For


Loop

Since we are on the subject of Java 5.0


enhancements with generics, let us continue
and check out the special for..each loop
structure. This loop structure was first
shown with the static arrays in the last
chapter. It was necessary to wait for the
array structure because the for..each loop
cannot work with proimitive data types.
You need a data structure and since

Chapter XIII The List Interface and ArrayList Class 705


ArrayList is a data structure, let us check
and see how the new loop stacks up.
Program Java1320.java, in figure 13.21,
presents three displays. The first output is
done directly with println and the names
object. You have seen this feature before. It
works fine with ArrayList objects, but not
static arrays.

The second output uses the original for loop


and visits every element of the names array.
The loop counter variable is used to access
each array element starting with index 0 and
continue until the names.size() - 1 index.
This works fine for the static array and the
dynamic array.

Finally, the for..each loop is used. Note the


convention of selection variable name of
type String to represent the single element.
This convention provides readability. We
can now read the loop statement as: for
each String element, called name in the
object names, display the value of name.

706 Exposure Java 2020, APCS Edition 06-06-10


Figure 13.21
// Java1320.java
// The final program in this chapter
shows three ways to display the
// members of an <ArrayList> object.
Note that the enhanced <for>
// loop works very well with <ArrayList>
objects.

import java.util.ArrayList;

public class Java1320


{
public static void main(String args[])
{
System.out.println();

System.out.println("Java1319.java\n");

ArrayList<String> names = new


ArrayList<String>();
names.add("Isolde");
Chapter XIII The List Interface and ArrayList Class 707
names.add("John");
names.add("Greg");
names.add("Maria");
names.add("Heidi");

System.out.println(names);
System.out.println();

for (int index = 0; index <


names.size(); index++)

System.out.println(names.get(index));
System.out.println();

for (String name: names)


System.out.println(name);
System.out.println();
}
}

708 Exposure Java 2020, APCS Edition 06-06-10


Figure 13.21 Continued
Java1320.java Output

Java1320.java

[Isolde, John, Greg, Maria,


Heidi]

Isolde
John
Greg
Maria
Heidi

Isolde
John
Greg
Maria
Heidi

Chapter XIII The List Interface and ArrayList Class 709


13.9 Summary

Java has two array data structures. There is


the static array, shown in the last chapter,
which cannot be resized during program
execution. The static array also does not
have any methods. However, on the plus
side static arrays can be multi- dimensional
and they have initializer lists.

The second array, introduced in this chapter,


is the dynamic array called ArrayList. The
dynamic array can be resized during
program execution and there are many
methods to process the data.

The ArrayList class implements the List


subinterface, which in turn comes from the
very general Collection interface. Interfaces

710 Exposure Java 2020, APCS Edition 06-06-10


only contain abstract method headings and
cannot be instantiated.

The ArrayList class has many methods.


The six most common methods are shown
next and they are also tested on the AP
Exam.

ArrayList Method add

names.add("Tom");

The add method allocates space for the


newly enlarged array and then stores
the new array element at the end of the
ArrayList object.

ArrayList Method size

int count = names.size();

Chapter XIII The List Interface and ArrayList Class 711


The size method returns the number of
elements of the ArrayList object
names.

ArrayList Method get

System.out.println(names.get(3));

The get method accesses a specified


array element. The parameter of the
get method is the index of the ArrayList
object and starts at 0.

Any attempt to access an element at a


non-existing index results in an
IndexOutOfBoundsException error.

ArrayList Method set

names.set(4,"Tom");

The set method uses the first parameter


as the index location to find an array
712 Exposure Java 2020, APCS Edition 06-06-10
element and then replaces it with the
value of the second set parameter. You
will get an error if you try to access an
index location, which has not been
allocated yet.

ArrayList Method remove

names.remove(3);

The remove method removes the array


element at the index location of its
parameter and decreases the object
size by one array element.

You will get an error if you try to access


an index location, which does not exist.

ArrayList Method add (second


overloaded add)

names.add(3,"Kathy");

Chapter XIII The List Interface and ArrayList Class 713


The overloaded add(3,"Kathy") method
adds or rather inserts a new array
element at the indicated index.

ArrayList objects cannot store primitive


data values directly. Some wrapper class,
like Integer, Double or Boolean must be
used to store simple data values.

Prior to Java 5.0 a program could not tell the


type of value stored in an object, like an
ArrayList object. Frequently casting was
necessary to assign values. With Java 5.0
generics are possible, which means that at
instatiation the data type of the ArrayList
element is specified.

The enhanced for..each loop, introduced


with static arrays also works very well with
dynamic arrays.

714 Exposure Java 2020, APCS Edition 06-06-10

You might also like