CSO_Gaddis_Java_Chapter07_6ge
CSO_Gaddis_Java_Chapter07_6ge
R7
Arrays and
the
ArrayList
Class
• 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 0 0 0 0 0
index 0 index 1 index 2 index 3 index 4 index 5
Array element values are initialized to 0.
Array indexes always start at 0.
©2016 Pearson Education, Ltd.
Creating Arrays
• It is possible to declare an array reference and create it
in the same statement.
int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
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];
2 4 6 8 10
array1 holds an
Address
address to the array
Example:
array2 holds an
SameArray.java
Address
address to the array
if (arraysEqual)
System.out.println("The arrays are equal.");
else
System.out.println("The arrays are not equal.");
PrintWriter outputFile =
new PrintWriter ("Values.txt");
outputFile.close();
Address
names[0] null
names[1] null
names[2] null
names[3] null
Address
System.out.println(names[0].toUpperCase());
char letter = names[3].charAt(0);
accounts[1] Address
balance: 0.0
accounts[2] Address
accounts[3] Address balance: 0.0
accounts[4] Address
©2016 Pearson Education, Ltd.
The Sequential Search Algorithm
• A search algorithm is a method of locating a specific
item in a larger collection of data.
• The sequential search algorithm uses a loop to:
– sequentially step through an array,
– compare each element with the search value, and
– stop when
• the value is found or
• the end of the array is encountered.
• See example: SearchArray.java
row 1
row 2
row 3
• 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.
• 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}
• Declares an array with three rows and three columns.
• Example: CommandLine.java
• It is not required that the name of main’s
parameter array be args.
import java.util.ArrayList;
• Example: ArrayListDemo1.java
ArrayList<BankAccount> accountList =
new ArrayList<BankAccount>();
See: ArrayListDemo6.java