Arrays and The Arraylist Class: Starting Out With Java: From Control Structures Through Objects Fifth Edition
Arrays and The Arraylist Class: Starting Out With Java: From Control Structures Through Objects Fifth Edition
Chapter Topics
Chapter 7 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
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-2
Chapter Topics
Chapter 7 discusses the following main topics:
The Sequential Search Algorithm Parallel Arrays Two-Dimensional Arrays Arrays with Three or More Dimensions The Selection Sort and the Binary Search Command-Line Arguments The ArrayList Class
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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
0
index 1
0
index 2
0
index 3
0
index 4
0
index 5
Creating Arrays
It is possible to declare an array reference and create it in the same statement.
int[] numbers = new int[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];
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-7
0
numbers[1]
0
numbers[2]
0
numbers[3]
0
numbers[4]
0
numbers[5]
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-8
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-9
Bounds Checking
Array indexes always start at zero and continue to (array length - 1).
int values = new int[10];
This array would have indexes 0 through 9. See example: InvalidSubscript.java In for loops, it is typical to use i, j, and k as counting variables.
It might help to think of i as representing the word index.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-13
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-14
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.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-17
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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]); }
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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];
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-20
If the first (10 element) array no longer has a reference to it, it will be garbage collected.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-21
Address
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-22
Address
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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 array2 holds an address to the array
8 10
Address
Example: SameArray.java
Address
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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];
This code copies each element of firstArray to the corresponding element of secondArray.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-25
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-26
5 10 15 20 25 30 35 40
Address
Example: PassArray.java
public static void showArray(int[] array) { for (int i = 0; i < array.length; i++) System.out.print(array[i] + " "); }
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-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.");
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-28
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-30
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-32
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-33
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-34
The getArray method is a public static method that returns an array of doubles. See example: ReturnArray.java
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-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
Bill
names[1]
names[2] names[3]
address
address address
Susan
Steven Jean
Example: MonthDays.java
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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] names[1] names[2] names[3] null null null null
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-37
String Arrays
When an array is created in this manner, each element of the array must be initialized.
The names variable holds the address to the array. Address names[0] names[1] names[2] names[3] null null null null Bill Susan Steven Jean names[0] names[1] names[2] names[3] = = = = "Bill"; "Susan"; "Steven"; "Jean";
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-38
Each element of a String array is a String object. Methods can be used by using the array name and index as before.
System.out.println(names[0].toUpperCase()); char letter = names[3].charAt(0);
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-39
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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] accounts[1] accounts[2] accounts[3] accounts[4] null null null null null
7-41
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Arrays of Objects
Each element needs to be initialized.
for (int i = 0; i < accounts.length; i++) accounts[i] = new BankAccount();
0.0
0.0
0.0
balance:
balance:
0.0
0.0
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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
row 0 row 1 row 2 row 3
column 1
column 2
column 3
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-45
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-46
Address
row 0 row 1 row 2
column 0
column 1
column 2
column 3
scores[0][0] scores[0][1] scores[0][2] scores[0][3] scores[1][0] scores[1][1] scores[1][2] scores[1][3] scores[2][0] scores[2][1] scores[2][2] scores[2][3]
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-47
Address
row 0 row 1 row 2
column 0
column 1
column 2
column 3
0 0 0
0 0 95
0 0 0
0 0 0
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-48
for (int row = 0; row < 3; row++) Number of { columns, not the for (int col = 0; col < 4; col++) largest subscript { System.out.print("Enter a score: "); scores[row][col] = keyboard.nextDouble(); } keyboard references a }
Scanner object
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-49
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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}
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-51
produces:
column 0 column 1 column 2
Address
row 0 row 1 row 2
1 4 7
2 5 8
3 6 9
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-52
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-53
See example: Lengths.java The array can have variable length rows.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Number of rows
7-54
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-55
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-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][];
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-59
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-60
Selection Sort
In a selection sort:
The smallest value in the array is located and moved to element 0. Then the next smallest value is located and moved to element 1. This process continues until all of the elements have been placed in their proper order. See example: SelectionSortDemo.java
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-61
Binary Search
A binary search:
requires an array sorted in ascending order. starts with the element in the middle of the array. If that element is the desired value, the search is over. Otherwise, the value in the middle element is either greater or less than the desired value If it is greater than the desired value, search in the first half of the array. Otherwise, search the last half of the array. Repeat as needed while adjusting start and end points of the search.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-62
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.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-63
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.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-64
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-65
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-66
Creating an ArrayList
ArrayList<String> nameList = new ArrayList<String>();
Notice the word String written inside angled brackets <> This specifies that the ArrayList can hold String objects.
If we try to store any other type of object in this ArrayList, an error will occur.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-67
Using an ArrayList
To populate the ArrayList, use the add method:
nameList.add("James"); nameList.add("Catherine");
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-68
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
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-69
Using an ArrayList
The ArrayList class's toString method returns a string
representing all items in the ArrayList
System.out.println(nameList);
The ArrayList class's remove method removes designated item from the ArrayList
nameList.remove(1); This statement removes the second item.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-70
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
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);
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-72
Using an ArrayList
You can store any type of object in an ArrayList
ArrayList<BankAccount> accountList = new ArrayList<BankAccount>();
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
7-73
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 BankAccount objects to the ArrayList. BankAccount(100.0)); BankAccount(500.0)); BankAccount(1500.0));
// Display each item. for (int index = 0; index < list.size(); index++) { BankAccount account = list.get(index); System.out.println("Account at index " + index + "\nBalance: " + account.getBalance()); }
See: ArrayListDemo6.java
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-74
Using an ArrayList
The diamond operator
Beginning in Java 7, you can use the <> operator for simpler ArrayList declarations:
No need to specify the data type here.
ArrayList<String> list = new ArrayList<>();
Java infers the type of the ArrayList object from the variable declaration.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.