7. Chapter_7 - Arrays & the ArrayList
Copyright Information
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Book Title: STARTING OUT WITH JAVATM 7th Edition
Chapter: Chapter 7 Arrays and the ArrayList Class
Chapter Topics: Overview (1 of 2)
Introduction to Arrays: Understanding the basic structure and purpose of arrays in programming.
Processing Array Contents: Methods for accessing and modifying data within arrays.
Passing Arrays as Arguments to Methods: How to pass arrays into functions.
Some Useful Array Algorithms and Operations: Common algorithms such as searching and sorting.
Returning Arrays from Methods: How functions can return an array.
String Arrays: Utilizing arrays specifically for String objects.
Arrays of Objects: Working with arrays that hold object references.
Chapter Topics: Overview (2 of 2)
The Sequential Search Algorithm: Method for finding elements in an array sequentially.
Parallel Arrays: Use of multiple arrays to hold related data.
Two-Dimensional Arrays: Arrays structured in rows and columns.
Arrays with Three or More Dimensions: Higher-dimensional arrays for complex data.
The Selection Sort and the Binary Search: Algorithms for sorting and searching.
Command-Line Arguments: Passing parameters to Java programs from the command line.
The ArrayList Class: Introduction to dynamic array lists in Java.
Introduction to Arrays
Primitive variables hold one value, whereas arrays can store collections of values.
Arrays can hold any data type, but must store only one type at a time.
Arrays are indexed lists of data elements, allowing for easy access and manipulation.
Creating Arrays (1 of 3)
Arrays are objects and require an object reference.
Example:
int[] numbers;
To create an array:
Example:
numbers = new int[6];
Array elements initialize to 0 by default, with indexes starting from 0.
Example of indexed values from an integer array:
0 index 00 index 10 index 20 index 30 index 40 index 5
Creating Arrays (2 of 3)
Arrays can be declared and created in one statement:
Example:
int[] numbers = new int[6];
Arrays can hold any type of data:
Examples:
float[] temperatures = new float[100];char[] letters = new char[41];long[] units = new long[50];double[] sizes = new double[1200];
Creating Arrays (3 of 3)
Array size must be a non-negative integer. It can be a literal, constant, or variable:
Example:
int[] numbers = new int[ARRAY_SIZE];Using a constant:
final int ARRAY_SIZE = 6;
Once an array is created, its size cannot be changed.
Accessing the Elements of an Array
Arrays are accessed using a reference name and a subscript:
Example:
numbers[0] = 20;
Example showing assignment:
numbers[0] 0numbers[1] 0numbers[2] 0numbers[3] 0numbers[4] 0numbers[5] 20
Inputting and Outputting Array Elements
Treat array elements like variables, accessed by name and subscript:
Utilized similar to single variables.
Example references and use of
for loopcounters can be used:Refer to
ArrayDemo1.javaandArrayDemo2.javafor practical examples.
Bounds Checking
Array indexes range from 0 to (length - 1).
Example:
int values = new int[10];Valid indexes: 0 - 9.
Loop controls commonly use increment variables such as
i,j,k.
Off-by-One Errors
Common errors in accessing arrays due to incorrect loop conditions.
Example demonstrating an off-by-one error:
int[] numbers = new int[100];Incorrect:
for (int i = 1; i <= 100; i++)Corrected Loop: Should use
i < 100to avoidArrayIndexOutOfBoundsException.
Array Initialization
Initialization lists can be used for quick population of arrays:
Example:
int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
Each element assigned in order from the list:
days[0]= 31,days[1]= 28, etc.
Alternate Array Declaration
Arrays can be declared using different syntaxes:
Example:
int numbers[];is valid, butint[] numbers;is preferred.
Multiple arrays can be declared on one line:
Example:
int[] numbers, codes, scores;
Processing Array Contents (1 of 2)
Array data processing similar to variable manipulation:
Example:
grossPay = hours[3] * payRate;
Pre and post increment operations:
Example:
++score[2];andscore[4]++;illustrated inPayArray.java.
Processing Array Contents (2 of 2)
Array elements can participate in relational operations:
Example:
if(cost[20] < cost[0]) {...}.
They can also be used in loop conditions:
Example:
while(value[count] != 0) {...}.
Array Length
Arrays in Java provide a public
lengthfield, indicating their size:Example:
double[] temperatures = new double[25];length is 25.
To get the size value:
Example:
int size = temperatures.length;yields 25.
Array Size (1 of 2)
Using
lengthallows automatic sizing in loops:Example:
for(int i = 0; i < temperatures.length; i++) {...}.
Array Size (2 of 2)
User-defined sizes for arrays can be implemented:
Example:
int numTests; int[] tests; Scanner keyboard = new Scanner(System.in); numTests = keyboard.nextInt(); tests = new int[numTests];
The Enhanced for Loop (1 of 2)
Simplifies array processing but is read-only:
General format:
for(datatype elementVariable : array) {...}.
The Enhanced for Loop (2 of 2)
Example of enhanced for loop:
int[] numbers = {3, 6, 9}; for(int val : numbers) { System.out.println("The next value is " + val); }
Reassigning Array References (1 of 3)
An existing array reference can be reassigned:
Example:
numbers = new int[5];automatically leads to garbage collection of the old reference if no longer used.
Reassigning Array References (2 of 3)
Visualization reference:
int[] numbers = new int[10];-> hold address of array, and reassignment leads to new address ofint[5].
Reassigning Array References (3 of 3)
Garbage Collection process in Java: old references are marked inactive when new references take over.
Copying Arrays (1 of 2)
Incorrect approach:
Example:
int[] array2 = array1;does not duplicate array.Each reference points to the same memory location, leading to changes reflected across both.
Copying Arrays (2 of 2)
Proper copying approach involves deep copying individual elements:
Example:
for (int i = 0; i < firstArray.length; i++) { secondArray[i] = firstArray[i]; }
Passing Array Elements to a Method
Individual array elements passed as variables:
Example:
PassElements.java.
More commonly entire arrays are passed to functions for processing.
Passing Arrays as Arguments
Array references can be passed to methods, similar to other object references:
Example:
public static void showArray(int[] array) { ... }
Comparing Arrays
Use of
==operator on arrays only compares references:Mistake example:
if (firstArray == secondArray) {...}
Comparing Arrays: Example
Size comparison before checking individual elements:
Determine equality based on both length and content of arrays:
if (firstArray.length != secondArray.length) {...}
Useful Array Operations (1 of 2)
Finding the highest value in the array:
int highest = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] > highest) highest = numbers[i]; }Similarly finding the lowest value:
int lowest = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] < lowest) lowest = numbers[i]; }
Useful Array Operations (2 of 2)
Summing elements in an array:
int total = 0; for (int i = 0; i < units.length; i++) { total += units[i]; }Averaging elements:
double average = total / scores.length;
Partially Filled Arrays
When data volume is uncertain, maximum expected size is used with a tracking variable for valid data counts:
int[] array = new int[100]; int count = 0; // Counter variable
Arrays and Files (1 of 2)
Saving array contents to a file:
PrintWriter outputFile = new PrintWriter("Values.txt"); for (int i = 0; i < numbers.length; i++) { outputFile.println(numbers[i]); } outputFile.close();
Arrays and Files (2 of 2)
Reading contents from file into an array:
Scanner inputFile = new Scanner(file); while (inputFile.hasNext() && i < numbers.length) { numbers[i] = inputFile.nextInt(); i++; } inputFile.close();
Returning an Array Reference
Returning methods can provide array references:
Example:
public static double[] getArray() { return array; }
String Arrays (1 of 3)
Arrays can store String objects:
Example:
String[] names = { "Bill", "Susan", "Steven", "Jean" };Each entry holds reference to the respective String object.
String Arrays (2 of 3)
When not immediately initialized, use the
newkeyword:String[] names = new String[4];
String Arrays (3 of 3)
After creation via
new, elements must be initialized individually:Example:
names[0] = "Bill"; names[1] = "Susan"; //... and so on
Calling String Methods On Array Elements
Invoking methods on String elements of an array:
Example:
System.out.println(names[0].toUpperCase());
The length Field & The length Method
Difference between array length (field) and String length (method):
Array length access example:
for (int i = 0; i < names.length; i++) { System.out.println(names[i].length()); }
Arrays of Objects (1 of 2)
Arrays can manage objects like String and custom classes:
Example:
BankAccount[] accounts = new BankAccount[5];
Arrays of Objects (2 of 2)
Object arrays require initialization for each element:
Example:
for (int i = 0; i < accounts.length; i++) { accounts[i] = new BankAccount(); }
The Sequential Search Algorithm
Sequential search through an array:
Compare each element in sequence until the target value is found.
Two-Dimensional Arrays (1 of 2)
Arrays can be structured as two-dimensional grids (arrays of arrays):
Visualization: rows and columns organization.
Two-Dimensional Arrays (2 of 2)
Declaration requires two dimension specifications:
Example:
double[][] scores = new double[3][4];
Accessing Two-Dimensional Array Elements (1 of 5)
Accessing elements involves using two subscripts for positioning:
Example:
scores[row][column].
Accessing Two-Dimensional Array Elements (2 of 5)
Visual representation of index references required:
Example:
scores[0][1]for row 0 and column 1.
Accessing Two-Dimensional Array Elements (3 of 5)
Modifying a two-dimensional array involves both subscripts:
Example:
scores[2][1] = 95;
Accessing Two-Dimensional Array Elements (4 of 5)
Nested loops for filling values in two-dimensional arrays:
Use outer and inner loops for rows and columns respectively:
for (int row = 0; row < 3; row++) { for (int col = 0; col < 4; col++) { scores[row][col] = keyboard.nextDouble(); } }
Accessing Two-Dimensional Array Elements (5 of 5)
Printing contents also requires two nested loops:
for (int row = 0; row < scores.length; row++) { for (int col = 0; col < scores[row].length; col++) { System.out.println(scores[row][col]); } }
Initializing a Two-Dimensional Array (1 of 2)
Creation with manual initialization using braces for each row:
Example:
int[][] numbers = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Initializing a Two-Dimensional Array (2 of 2)
Java can automatically allocate values if provided as nested arrays:
Variable holds the references to the initialized arrays.
The length Field (1 of 2)
Length fields for two-dimensional arrays return number of rows:
Example demonstrating variable count abilities of each row’s columns:
for (int row = 0; row < numbers.length; row++) { System.out.println(numbers[row].length); }
The length Field (2 of 2)
Each row can have different column lengths:
Example:
int[][] numbers = { { 1, 2, 3, 4 }, { 5, 6, 7 }, { 9, 10, 11, 12 } };
Summing The Elements of a Two-Dimensional Array
String operation to sum all elements:
int total = 0; for (int row = 0; row < numbers.length; row++) { for (int col = 0; col < numbers[row].length; col++) { total += numbers[row][col]; } }
Summing The Rows of a Two-Dimensional Array
Individual row totals can also be summed:
for (int row = 0; row < numbers.length; row++) { total = 0; for (int col = 0; col < numbers[row].length; col++) { total += numbers[row][col]; } System.out.println("Total of row " + row + " is " + total); }
Summing The Columns of a Two-Dimensional Array
To sum column values, outer loop controls for columns, inner for rows:
for (int col = 0; col < numbers[0].length; col++) { total = 0; for (int row = 0; row < numbers.length; row++) { total += numbers[row][col]; } System.out.println("Total of column " + col + " is " + total); }
Passing and Returning Two-Dimensional Array References
Passing two-dimensional arrays to methods identical to single arrays.
Method declarations handle parameters as needed:
public static void processArrays(int[][] arr) { // processing code }
Ragged Arrays
Variable-length rows create ragged arrays:
Example declaration that supports this:
int[][] ragged = new int[4][];and further initialization per row:
ragged[0] = new int[3]; ragged[1] = new int[4];
More Than Two Dimensions
There’s no limit on the dimensions of arrays in Java:
However, higher dimensions may be complex:<br>
Usage largely based on specific computational needs.
Bubble Sort
Sorting mechanism based on comparisons and swaps:
Example:
if (array[j] > array[j+1]) { // swap logic }
Selection Sort
In selection sort, smallest element is moved to the front:
Process repeats until complete order is achieved.
Binary Search
Effective searching method with sorted arrays:
It recursively reduces items for comparison, adjusting bounds each iteration:
Command-Line Arguments (1 of 2)
Java receives command-line arguments for var input:
Defined in the main method:
public static void main(String[] args) {...}.
Command-Line Arguments (2 of 2)
Upon execution, command-line inputs route into the
args:Example inputs: java CommandLine How does this work?
Variable-Length Argument Lists
Use of varargs for flexible parameter input:
Treat as arrays internally while allowing flexible number of arguments passed:
The ArrayList Class
ArrayList adapts similar to arrays, but allows dynamic resizing:
Pros: growth and shrinkage automatically as needed.
Creating an ArrayList
Method to create an ArrayList with specified type:
Example:
ArrayList<String> nameList = new ArrayList<String>();
Using an ArrayList (1 of 8)
Add elements to the list using
.add():Example:
nameList.add("James");
Using an ArrayList (2 of 8)
Accessing array elements via
.get():Example:
nameList.get(1);returns element at index 1.
Using an ArrayList (3 of 8)
Retrieving the string representation via
.toString():Example:
System.out.println(nameList);
Using an ArrayList (4 of 8)
Modifying content using
.set()to swap values:Example:
nameList.set(1, "Becky");
Using an ArrayList (5 of 8)
The default capacity of an ArrayList is 10, but can be modified:
Example:
ArrayList<String> list = new ArrayList<String>(100);
Using an ArrayList (6 of 8)
ArrayList accepts custom objects using generic types:
Example:
ArrayList<BankAccount> accountList = new ArrayList<BankAccount>();
Using an ArrayList (7 of 8)
Full example of creating an ArrayList for an object type:
ArrayList<BankAccount> list = new ArrayList<BankAccount>();
Using an ArrayList (8 of 8)
Java 7 introduced diamond operator (<>) for type inference:
Note:
ArrayList<String> list = new ArrayList<>();utilizes inferred types.