Sub topic 3
Comparing and Printing Array Contents
An array is an object that holds a fixed number of values. To follow the examples, start JShell, Java’s interactive tool, by running jshell in a terminal. Enter the Java blocks in order.
Comparing and Printing Array Contents
The == operator checks whether two array references point to the same array. To compare their contents, use Arrays.equals. To print their contents, use Arrays.toString.
import java.util.Arrays;
int[] numbers = {3, 1, 2};
int[] copy = numbers.clone();
System.out.println(numbers == copy); // false
System.out.println(Arrays.equals(numbers, copy)); // true
System.out.println(Arrays.toString(numbers)); // [3, 1, 2]The copy is a separate array, but its values match. For arrays containing other arrays, use Arrays.deepEquals to compare their contents and Arrays.deepToString to print them.
Sorting and Searching Arrays
Sorting puts values in order. Arrays.sort changes the array it receives. Arrays.binarySearch finds a value in a sorted array and returns its index, or position.
Arrays.sort(copy);
System.out.println(Arrays.toString(copy)); // [1, 2, 3]
System.out.println(Arrays.binarySearch(copy, 2)); // 1Search the sorted copy, not the original. A negative result means the value was not found. Searching an unsorted array can give an incorrect result.
Arrays and Variable-Arity Methods
A variable-arity parameter, or varargs parameter, lets a method accept zero or more values. Inside the method, those values are an array.
int sum(int... values) {
int total = 0;
for (int value : values) {
total += value;
}
return total;
}
System.out.println(sum(2, 3)); // 5
System.out.println(sum(numbers)); // 6A varargs parameter must be the method’s last parameter.
Covariance, Runtime Checks, and Generic Array Restrictions
Covariance means an array of a more specific object type can be used through a reference to a more general array type.
Object[] slots = new String[1];The actual array still accepts only strings. Putting another kind of object into slots causes an ArrayStoreException while the program runs.
A generic type takes a type argument, as List<String> does. Java does not allow new List<String>[3]. A List<List<String>> is one alternative.
Processing Arrays with Streams
A stream is a way to process values as a sequence. For an int array, Arrays.stream can create a stream whose sum method adds the values.
System.out.println(Arrays.stream(numbers).sum()); // 6This does not change numbers.
Choosing Between Arrays and Collections
A collection is an object that groups values. Choose an array when its fixed length is useful. Choose a list, such as an ArrayList, when you need to add or remove items. Lists hold objects, so use Integer rather than int for a list of whole numbers.
Exercise
Why should you sort a copy before searching it with Arrays.binarySearch?
Show answer
The search needs sorted data, and sorting a copy leaves the original order unchanged.