Mastering Java Arrays: Over 6 Essential Methods Explained

Arrays are a fundamental part of Java. In this article, we will explore over six super useful and helpful methods from the java.util.Arrays class that you can incorporate into your own code.

For additional information on any of these methods, you can always refer to Oracle's official documentation, which provides a comprehensive list of every method, detailed explanations, examples, parameters, and return values. However, the goal of this article is to explain them well enough so you don't have to refer to the docs.

1. The asList() Method

This method takes in an array and returns it in the form of a List. A List is a data structure from the Java Collections framework that offers more functionality and flexibility when dealing with a collection of elements than a standard array does.

Consider an array with three elements:

String[] array = {"chicken", "bacon", "avocado"};

The syntax for converting this to a List is quite simple. All methods in the Arrays class are static, meaning you don't need to create an Arrays object to invoke them. You can simply use the class name, the dot operator, and the method name.

// The asList method returns the array as a List
List<String> list = Arrays.asList(array);

// Now we can loop through the list
for (String item : list) {
    System.out.print(item + " ");
}

When you run this, the output will be:

chicken bacon avocado 

The primary reason to do this is that a List provides more functionality. With an array, you cannot add or remove elements. A List, however, allows you to get, add, and remove elements, offering greater flexibility.

2. The fill() Method

When you instantiate an array like new int[5], it creates an array of five elements, with each element set to a default value. For integers, the default is 0.

int[] numbers = new int[5];
// If you print this array, all elements will be 0.

But what if you need a different default value? For instance, in a game where five users all start with 100 points. This is where the fill() method is invaluable.

int[] scores = new int[5];
Arrays.fill(scores, 100);

// Now, every element in the scores array is 100.

3. The copyOf() Method

This method provides an easy way to duplicate an existing array. A common mistake is to assign one array to another, like array2 = array1. This does not create a copy; instead, it makes array2 point to the same memory location as array1. Modifying one will affect the other.

Incorrect Way (Reference, not Copy): ```java int[] array1 = {1, 2, 3, 4, 5}; int[] array2 = array1;

array2[2] = 47; // This changes array1 as well System.out.println(array1[2]); // Prints 47 ```

To create a true, independent copy, use copyOf():

int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = Arrays.copyOf(array1, array1.length);

// Now, let's change an element in the new array
array2[2] = 47;

// Print elements of array1
for (int element : array1) {
    System.out.print(element + " "); // Output: 1 2 3 4 5 
}

System.out.println(); // New line

// Print elements of array2
for (int element : array2) {
    System.out.print(element + " "); // Output: 1 2 47 4 5 
}

As you can see, only the element in array2 was changed. The second parameter in copyOf is the length, so you can also copy a partial range of elements if needed.

4. The equals() Method

Another common pitfall is using array1 == array2 to check if two arrays are equal. This expression checks if the two variables point to the exact same object in memory, not if their contents are identical. To compare the actual contents of two different arrays, the equals() method is the correct choice.

String[] food1 = {"lettuce", "tomato", "onion"};
String[] food2 = {"lettuce", "tomato", "onion"};

boolean areTheyEqual = Arrays.equals(food1, food2);
System.out.println(areTheyEqual); // This will print "true"

// Now let's add an element to the second array
String[] food3 = {"lettuce", "tomato", "onion", "apples"};
areTheyEqual = Arrays.equals(food1, food3);
System.out.println(areTheyEqual); // This will print "false"

The method returns a boolean value indicating whether the arrays contain the same elements in the same order.

5. The compare() Method

The compare() method is similar to equals() but provides more detailed information. It compares two arrays lexicographically.

The syntax is Arrays.compare(array1, array2). - It returns 0 if the arrays are equal (same elements in the same order). - It returns a negative number if the first array is lexicographically smaller than the second. - It returns a positive number if the first array is lexicographically larger than the second.

String[] arr1 = {"l", "e", "t", "t", "u", "c", "e"};
String[] arr2 = {"l", "e", "t", "t", "u", "c", "e"};

int c = Arrays.compare(arr1, arr2);
System.out.println(c); // Prints 0 because they are equal

// Make arr1 lexicographically larger
String[] arr3 = {"z", "e", "t", "t", "u", "c", "e"};
c = Arrays.compare(arr3, arr2);
System.out.println(c); // Prints a positive number (14)

// Make arr1 lexicographically smaller
c = Arrays.compare(arr2, arr3);
System.out.println(c); // Prints a negative number (-14)

The returned number represents the difference at the first unequal element. You would use this instead of equals() when you need more than a simple true/false result, for example, to handle different outcomes based on which array comes "first."

6. The sort() Method

As its name implies, the sort() method sorts an array in ascending order.

int[] data = {10, 4, 19, 5, 2};
Arrays.sort(data);

for (int num : data) {
    System.out.print(num + " "); // Output: 2 4 5 10 19 
}

For primitive types like integers and doubles, Java knows how to sort them. However, if you have an array of custom objects (e.g., a Student object with name and age properties), the sort method doesn't know how to sort them by default. For such cases, you can provide a second parameter, a Comparator, which tells the sort method how to order the objects based on their properties.

7. The binarySearch() Method

This powerful method searches for a specified element in a sorted array and returns its index. If the element is not found, it returns a negative number.

Crucial Note: The array must be sorted before calling binarySearch(). The method's behavior is undefined on an unsorted array; it might work by chance, but it is not guaranteed. It is the developer's responsibility to sort the array first.

int[] sortedData = {2, 4, 5, 10, 19}; // Array is already sorted
int index = Arrays.binarySearch(sortedData, 19);
System.out.println(index); // Prints 4, the index of 19

If the array is not sorted, the result is unpredictable: java int[] unsortedData = {10, 4, 100, 5, 2}; int index = Arrays.binarySearch(unsortedData, 100); System.out.println(index); // Prints a negative value, indicating failure

Additionally, if the array contains duplicate values, binarySearch() does not guarantee which of the duplicates' indices will be returned.

int[] withDuplicates = {2, 5, 10, 10, 10, 19};
int index = Arrays.binarySearch(withDuplicates, 10);
// This might return 2, 3, or 4. The result is not consistent.

While many of these are methods you could implement on your own, it's highly encouraged to use the built-in methods whenever possible. They are generally safer, more optimized, and thoroughly tested.