0%

Methods of java.util.Arrays class

The class of java.util.Arrays contain various methods for manipulating arrays. This article introduces the most commonly used methods in this class.

asList( )

This method acts as a bridge between array-based and collection-based APIs in combination with Collection.toArray( ).

binarySearch( )

binarySearch: searches the specifies value of the array using the binary search algorithm. The array must be sorted.

return value type: int - the index of the array

Two main ways to use this method:

1
2
binarySearch(arr, key) // 1
binarySearch(arr, int fromIndex, int toIndex) // 2

Note: we can also use a comparator in this method.

copyOf( )

Usage:

1
copyOf(arr, int new Length)

If the new Length is smaller than the length of arr, then this method will return the first Length objects of the arr. Below is an example:

1
2
int[] a = {12, 32, 54, 232, 1212};
int[] b = Arrays.copyOf(a, 3); // b is [12, 32, 54]

copyOfRange( )

Usage:

1
copyOfRange(arr, int fromIndex, int toIndex)

equals( ) & deepEquals( )

Usage:

1
2
equals(arr1, arr2)
deepEquals(arr1, arr2)

The differences between the two methods: we can only use equals(arr1, arr2) if the arr1 and arr1 are one-dimensional. We can use deepEquals(arr1, arr2) if the array is multi-dimensional.

fill( )

This method assigns the value to each element of the array.

Usage:

1
2
fill(arr, val)
fill(arr, int fromIndex, int toIndex, val)

sort( )

Usage:

1
2
3
4
sort(arr)
sort(arr, int fromIndex, int toIndex)
sort(arr, Comparator<>())
sort(arr, int fromIndex, int toIndex, Comparator<> c)

toString()

This method returns a string representation of the array.

Usage:

1
toString(arr)