JAVA – USEFUL ARRAY TECHNIQUES

An array is a collection of variables of the same type. The length of an array is established when the array is created. After creation, its length is fixed.

In this tutorial, we will look at some advanced array techniques. I am assuming that you knew the basics about arrays in Java.

Convert Array to String

Java provides an ellegant ways to convert an array to string. The conversion of array to string can be very useful for printing the array. Here is an example of how to convert an array of int to String.

//Create an array of integer
int[] numbers = {12, 66, 45, 88};
    
//Convert the array to String
String str = Arrays.toString(numbers);

System.out.println(str);

Output:

The array converted to string is [12, 66, 45, 88]

Filling Arrays

The java.util.Arrays has a set of methods called fill() to fill up an one dimension array . The method assigns the specified data type value each element of the array. Here is an example of how to use this method to fill up a two dimensions array.

// Create a two dimensions arrays
int[][] M = new int[3][3];

// Fill M with the value 5
for (int[] arr : M)
    Arrays.fill(arr, 5);

// Display M
for (int[] arr : M) {
    System.out.println(Arrays.toString(arr));
}

Output:

[5, 5, 5]
[5, 5, 5]
[5, 5, 5]

There is a version of Arrays.fill() which takes a from and to index, so only elements with indexes in this interval are filled with the given value. Here is an example.

// Create an array
int[] arr = new int[10];
    
//Fill the firsts 5 elements with 2
Arrays.fill(arr, 0, 5, 2);
    
// Fill the next 5 elements with 4
Arrays.fill(arr, 5, 10, 4);
    
System.out.println(Arrays.toString(arr));

Output:

[2, 2, 2, 2, 2, 4, 4, 4, 4, 4]

Sorting

There are many times when it is necessary to put the elements of an array in order from highest to lowest (descending) or vice versa (ascending). Java provide the Arrays.sort() method to sort an array. Here is an example :

// Create an array
String[] arr = { "shanghai", "paris", "beijing", "rome", "quebec" };

// sort the array in the reverse order of the natural ordering
Arrays.sort(arr);

System.out.println(Arrays.toString(arr));

Output:

[beijing, paris, quebec, rome, shanghai]

There is a version of Arrays.sort() that take a Comparator as second parameter. We can then use that version of Arrays.sort() to sort array in descending order.

The java.util.Comparator.reverseOrder() returns a comparator that imposes the reverse of the natural ordering. It only works on non-primitive array types.

Here is an example of how to use Arrays.sort() with java.util.Comparator.reverseOrder() to sort an array in descending order.

// Create an array
String[] arr = { "shanghai", "paris", "beijing", "rome", "quebec" };

// sort the array in the reverse order of the natural ordering
Arrays.sort(arr, Comparator.reverseOrder());

System.out.println(Arrays.toString(arr));

Output:

[shanghai, rome, quebec, paris, beijing]

We can also use a custom comparator in order to indicate a specific sorting logic. Let’s say that we want to sort the array in the above example by the length of the elements its contains. We can proceed as follow:

// Create an array
String[] arr = { "shanghai", "paris", "beijing", "rome", "quebec" };

// Define a comparator to sort by the length of the string 
Comparator<String> cmp = (s1, s2) -> {
    if (s1.length() > s2.length())
        return 1;
    else if (s2.length() > s1.length())
        return -1;
    return 0;
};
    
// sort the array using the comparator
Arrays.sort(arr, cmp);

System.out.println(Arrays.toString(arr));

Output:

[rome, paris, quebec, beijing, shanghai]

Searching

Java also provides the method Arrays.binarySearch() to search in array, but only if the array is already sorted. When searching in array, we have three scenarios:

  • Target element found in sorted array => The method returns the index of match.
  • Target element not found in sorted array => The method returns a negative value showing one smaller than the negative of index where a match needs to be inserted to preserve the sorted order.
  • Unsorted array => The result returned by the method is not predicable.

Here is an example of using Arrays.binarySearch() to search in array.

// Create an array
String[] arr = { "shanghai", "paris", "beijing", "rome", "quebec" };

// sort the array
Arrays.sort(arr);
    
/* Search in the array */
//Case the element is in the array
int index = Arrays.binarySearch(arr, "rome");
System.out.println("The search result of \"rome\" is " + index);
    
//Case the element is not in the array
index = Arrays.binarySearch(arr, "alpha");
System.out.println("The search result of \"alpha\" is " + index);

Output:

The search result of "rome" is 3
The search result of "alpha" is -1

There is a version Arrays.binarySearch() that take a Comparator as second parameter. We can use that version of Arrays.binarySearch() in the case we used a comparator during the sorting.

Checking if Arrays are Equal

Java has a convenient way to check if two arrays are equal. Two arrays are considered equal if the arrays have the same length, and the elements are equal to each other in the order they are found in the array. Here is an example of how to use Arrays.equals() to check if two arrays are equal.

// Create a first array
int[] arr1 = { 2, 2, 2, 2, 2 };
    
// Create a second array and fill it with 2
int[] arr2 = new int[5];
Arrays.fill(arr2, 2);
    
// Create a third array and fill it with 7
int[] arr3 = new int[5];
Arrays.fill(arr3, 7);

// Check if arr1 and arr2 are equal
if (Arrays.equals(arr1, arr2)) 
    System.out.println("arr1 and arr2 are equal");
else
    System.out.println("arr1 and arr2 are not equal");
    
// Check if arr1 and arr3 are equal
if (Arrays.equals(arr1, arr3)) 
    System.out.println("arr1 and arr3 are equal");
else
    System.out.println("arr1 and arr3 are not equal");

Output:

arr1 and arr2 are equal
arr1 and arr3 are not equal

Conclusion

In this tutorial, we have looked at some useful operations provided by methods in the java.util.Arrays class. We have seen operations like conversion of an array in to String; filling an array; sorting an array; searching in an array and checking if two arrays are equal. For more array manipulation method, you can read the official Java documentation of Arrays.

Thanks for reading. Please leave feedback and questions in the comments!

You May Also Like

About the Author: Miguel KAKANAKOU

3 Comments

Leave a Reply to Alok Sachan Cancel reply

WP to LinkedIn Auto Publish Powered By : XYZScripts.com
%d bloggers like this: