Arrays and The Arraylist Class: Starting Out With Java: From Control Structures Through Data Structures Second Edition
Arrays and The Arraylist Class: Starting Out With Java: From Control Structures Through Data Structures Second Edition
Chapter 8:
Arrays and the ArrayList Class
Starting Out with Java:
From Control Structures through Data Structures
Second Edition
by Tony Gaddis and Godfrey Muganda
Chapter Topics
Chapter 8 discusses the following main topics:
Introduction to Arrays
Processing Array Contents
Passing Arrays as Arguments to Methods
Some Useful Array Algorithms and Operations
Returning Arrays from Methods
String Arrays
Arrays of Objects
8-2
Chapter Topics
Chapter 8 discusses the following main topics:
8-3
Introduction to Arrays
Primitive variables are designed to hold only
one value at a time.
Arrays allow us to create a collection of like
values that are indexed.
An array can store any type of data but only
one type of data at a time.
An array is a list of data elements.
8-4
Creating Arrays
An array is an object so it needs an object reference.
// Declare a reference to an array that will hold integers.
int[] numbers;
The next step creates the array and assigns its address to the
numbers variable.
// Create a new array that will hold 6 integers.
numbers = new int[6];
0
index 0
index 1
index 2
index 3
index 4
index 5
8-5
Creating Arrays
It is possible to declare an array reference and create it
in the same statement.
int[] numbers = new int[6];
8-6
Creating Arrays
The array size must be a non-negative number.
It may be a literal value, a constant, or variable.
final int ARRAY_SIZE = 6;
int[] numbers = new int[ARRAY_SIZE];
8-7
numbers[0]
numbers[1]
numbers[2]
numbers[3]
numbers[4]
numbers[5]
8-8
8-9
Bounds Checking
Array indexes always start at zero and continue to
(array length - 1).
int values = new int[10];
8-10
Off-by-One Errors
It is very easy to be off-by-one when accessing arrays.
// This code has an off-by-one error.
int[] numbers = new int[100];
for (int i = 1; i <= 100; i++)
numbers[i] = 99;
Here, the equal sign allows the loop to continue on to index
100, where 99 is the last index in the array.
This code would throw an
ArrayIndexOutOfBoundsException.
8-11
Array Initialization
When relatively few items need to be initialized, an
initialization list can be used to initialize the array.
int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
etc.
8-12
8-13
8-14
8-15
Array Length
Arrays are objects and provide a public field named length
that is a constant that can be tested.
double[] temperatures = new double[25];
The length of this array is 25.
8-16
8-17
8-18
Array Size
The length constant can be used in a loop
to provide automatic bounding.
Index subscripts start at 0 and end at one less than the
array length.
for(int i = 0; i < temperatures.length; i++)
{
System.out.println("Temperature " + i ": "
+ temperatures[i]);
}
8-19
Array Size
You can let the user specify the size of an array:
int numTests;
int[] tests;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
tests = new int[numTests];
8-20
8-21
Address
8-22
Address
8-23
Copying Arrays
This is not the way to copy an array.
int[] array1 = { 2, 4, 6, 8, 10 };
int[] array2 = array1; // This does not copy array1.
2
array1 holds an
address to the array
Address
array2 holds an
address to the array
Address
8 10
Example:
SameArray.java
8-24
Copying Arrays
You cannot copy an array by merely assigning one
reference variable to another.
You need to copy the individual elements of one array to
another.
int[] firstArray = {5, 10, 15, 20, 25 };
int[] secondArray = new int[5];
for (int i = 0; i < firstArray.length; i++)
secondArray[i] = firstArray[i];
8-25
8-26
Address
5 10 15 20 25 30 35 40
Example: PassArray.java
8-27
Comparing Arrays
The == operator determines only whether array
references point to the same array object.
int[] firstArray = { 5, 10, 15, 20, 25 };
int[] secondArray = { 5, 10, 15, 20, 25 };
if (firstArray == secondArray) // This is a mistake.
System.out.println("The arrays are the same.");
else
System.out.println("The arrays are not the same.");
8-28
8-29
8-30
8-31
8-32
8-33
8-34
8-35
String Arrays
Arrays are not limited to primitive data.
An array of String objects can be created:
String[] names = { "Bill", "Susan", "Steven", "Jean" };
Address
names[0]
address
Bill
names[1]
address
Susan
names[2]
address
Steven
names[3]
address
Jean
Example:
MonthDays.java
8-36
String Arrays
If an initialization list is not provided, the new keyword must be
used to create the array:
String[] names = new String[4];
The names variable holds
the address to the array.
Address
names[0]
null
names[1]
null
names[2]
null
names[3]
null
8-37
String Arrays
When an array is created in this manner, each element of the
array must be initialized.
names[0]
names[1]
names[2]
names[3]
=
=
=
=
"Bill";
"Susan";
"Steven";
"Jean";
Address
names[0]
null
Bill
names[1]
null
Susan
names[2]
null
Steven
names[3]
null
Jean
8-38
toUpperCase
compareTo
equals
charAt
8-39
8-40
Arrays of Objects
Because Strings are objects, we know that arrays can contain
objects.
BankAccount[] accounts = new BankAccount[5];
The accounts variable holds the address
of an BankAccount array.
Address
accounts[0]
null
accounts[1]
null
accounts[2]
null
accounts[3]
null
accounts[4]
null
The array is an
array of references
to BankAccount
objects.
8-41
Arrays of Objects
Each element needs to be initialized.
for (int i = 0; i < accounts.length; i++)
accounts[i] = new BankAccount();
balance:
0.0
Address
balance:
0.0
balance:
0.0
balance:
0.0
balance:
0.0
accounts[0] Address
accounts[1] Address
accounts[2] Address
accounts[3] Address
accounts[4] Address
2012 Pearson Education, Inc. All rights reserved.
8-42
8-43
Two-Dimensional Arrays
A two-dimensional array is an array of arrays.
It can be thought of as having rows and columns.
column 0
column 1
column 2
column 3
row 0
row 1
row 2
row 3
8-44
Two-Dimensional Arrays
Declaring a two-dimensional array requires two sets of brackets
and two size declarators
The first one is for the number of rows
The second one is for the number of columns.
double[][] scores = new double[3][4];
rows
columns
The two sets of brackets in the data type indicate that the scores
variable will reference a two-dimensional array.
Notice that each size declarator is enclosed in its own set of
brackets.
2012 Pearson Education, Inc. All rights reserved.
8-45
8-46
Address
column 1
column 2
column 3
row 0
row 1
row 2
8-47
Accessing one of the elements in a twodimensional array requires the use of both
subscripts.
scores[2][1] = 95;
column 0
column 1
column 2
column 3
row 0
row 1
row 2
95
Address
8-48
8-49
8-50
Java automatically creates the array and fills its elements with
the initialization values.
row 0 {1, 2, 3}
row 1 {4, 5, 6}
row 2 {7, 8, 9}
8-51
produces:
column 0
column 1
column 2
row 0
row 1
row 2
Address
8-52
8-53
Number of rows
8-54
8-55
8-56
8-57
8-58
Ragged Arrays
When the rows of a two-dimensional array are of different
lengths, the array is known as a ragged array.
You can create a ragged array by creating a twodimensional array with a specific number of rows, but no
columns.
int [][] ragged = new int [4][];
=
=
=
=
new
new
new
new
int
int
int
int
[3];
[4];
[5];
[6];
8-59
8-60
Command-Line Arguments
A Java program can receive arguments from the operating
system command-line.
The main method has a header that looks like this:
public static void main(String[] args)
The main method receives a String array as a parameter.
The array that is passed into the args parameter comes from
the operating system command-line.
8-61
Command-Line Arguments
To run the example:
java CommandLine How does this work?
args[0]
args[0]
args[0]
args[0]
is
is
is
is
assigned
assigned
assigned
assigned
"How"
"does"
"this"
"work?"
Example: CommandLine.java
It is not required that the name of mains
parameter array be args.
2012 Pearson Education, Inc. All rights reserved.
8-62
8-63
Requires:
import java.util.ArrayList;
8-64
Creating an ArrayList
ArrayList<String> nameList = new ArrayList<String>();
8-65
Using an ArrayList
To populate the ArrayList, use the add method:
nameList.add("James");
nameList.add("Catherine");
// returns 2
8-66
Using an ArrayList
To access items in an ArrayList, use the get method
nameList.get(1);
In this statement 1 is the index of the item to get.
Example: ArrayListDemo1.java
8-67
Using an ArrayList
The ArrayList class's toString method returns a string
representing all items in the ArrayList
System.out.println(nameList);
8-68
Using an ArrayList
The ArrayList class's add method with one argument adds
new items to the end of the ArrayList
To insert items at a location of choice, use the add method with
two arguments:
nameList.add(1, "Mary");
This statement inserts the String "Mary" at index 1
8-69
Using an ArrayList
An ArrayList has a capacity, which is the number of items
it can hold without increasing its size.
The default capacity of an ArrayList is 10 items.
To designate a different capacity, use a parameterized
constructor:
ArrayList<String> list = new ArrayList<String>(100);
8-70
Using an ArrayList
You can store any type of object in an ArrayList
ArrayList<BankAccount> accountList =
new ArrayList<BankAccount>();
8-71
Using an ArrayList
// Create an ArrayList to hold BankAccount objects.
ArrayList<BankAccount> list = new ArrayList<BankAccount>();
// Add three
list.add(new
list.add(new
list.add(new
See: ArrayListDemo6.java
2012 Pearson Education, Inc. All rights reserved.
8-72