Section 7.5 Arrays
Library
Working with Java arrays can be tedious. Typically, we have to size new arrays and handle each element individually. Fortunately, the Java Core Library includes a class named
Arrays
providing a long list of static methods that we can use to operate on arrays. The Arrays
class static methods include a wide range of utilities that manipulate and manage arrays of many types, including the following. See examples of several of these methods in Listing 7.5.2. Note that the Arrays
class is in the java.util.Arrays
module and must be imported before its methods may be used.Arrays
class
Arrays method |
Description |
---|---|
Arrays.copyOf(…) |
copying an entire array |
Arrays.copyOfRange(…) |
copying a slice of an array |
Arrays.equals(…) |
element-by-element equality test |
Arrays.fill(…) |
filling with values |
Arrays.toString(…) |
converting to a String |
Arrays.sort(…) |
sort array elements |
Arrays.binarySearch(…) |
search array elements |
// ArraysMethods.java
import java.util.Arrays;
import java.util.Random;
public class ArraysMethods {
public static void main(String[] args) {
Random rnd = new Random(); // Random object
// Create an array of 1000 random integers in [100, 500)
// and print ends
int[] nums = new int[1000];
for (int i = 0; i < nums.length; i++) {
nums[i] = 100 + rnd.nextInt(400);
}
printEnds( "nums", nums );
// Create a copy of the array and print copy
int[] copy = Arrays.copyOf(nums, nums.length);
printEnds( "copy", copy );
// Check if they are the identical array
System.out.println("nums and copy" +
(nums == copy ? " ARE" : " ARE NOT") + " identical");
// Check equivalence element-by-element
System.out.println("nums and copy" +
(Arrays.equals(nums, copy) ? " ARE" : " ARE NOT") + " equivalent");
// Sort array and print
Arrays.sort(nums);
printEnds( "nums (sorted)", nums );
// Copy array ranges into two arrays and print
int[] firstHalf = Arrays.copyOfRange(nums, 0, 500);
int[] secondHalf = Arrays.copyOfRange(nums, 500, 1000);
printEnds( "firstHalf ", firstHalf );
printEnds( "secondHalf", secondHalf );
}
// Print array name and elements from both ends of array
public static void printEnds( String name, int[] arr ) {
System.out.print(name + ": ");
for (int i=0; i<5; i++) { // Print first 5
System.out.print( arr[i] + " ");
}
System.out.print( "... "); // Print last 5
for (int i=arr.length-5; i<arr.length; i++) {
System.out.print( arr[i] + " ");
}
System.out.println();
}
}
ArraysMethods.java
javac ArraysMethods.java java ArraysMethods nums: 277 217 458 299 117 ... 482 447 433 136 199 copy: 277 217 458 299 117 ... 482 447 433 136 199 nums and copy ARE NOT identical nums and copy ARE equivalent nums (sorted): 100 100 100 101 102 ... 498 498 498 499 499 firstHalf : 100 100 100 101 102 ... 301 302 302 303 303 secondHalf: 303 304 305 305 305 ... 498 498 498 499 499