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 | binarySearch(arr, key) // 1 |
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 | int[] a = {12, 32, 54, 232, 1212}; |
copyOfRange( )
Usage:
1 | copyOfRange(arr, int fromIndex, int toIndex) |
equals( ) & deepEquals( )
Usage:
1 | equals(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 | fill(arr, val) |
sort( )
Usage:
1 | sort(arr) |
toString()
This method returns a string representation of the array.
Usage:
1 | toString(arr) |