Array Utilities in Java
Arrays class is a part of the Java collection framework in the java.util package. It only consists of static methods and methods of the object class. Using Arrays, we can create, compare, sort, search, stream, and transform arrays. We can access the methods of this class easily by their class name itself.
Introduction to Arrays Class in Java
Java Array class was introduced in Java version 1.2. The methods that it consists of are used mostly for the manipulation of an array including all major operations like creating, sorting, searching comparing,, etc. We get overloaded methods for most of the data types by the arrays class. java.util.Arrays is a class that belongs to the java.util package.
Why do we need the Arrays class in Java?
This is because the methods provide provided by the Arrays class help us to perform useful tasks on arrays conveniently without the use of loops.
Now you might be wondering what the hierarchy of this class looks like?
The class hierarchy for Arrays class in Java:
The Arrays class is extended from the Object class and the methods that it provides are the methods of the object class.
Let's take a look at the syntax for the class declaration and the usage of arrays.
Syntax: Class Declaration
Syntax: In Order to Use Arrays
Methods in Java Array Class
The static methods of the Java Array class could be used to perform operations like:
- Filling the elements
- Sorting the elements
- Searching for the elements
- Converting the array elements to String
- Many more...
Let's take a closer look at all the methods provided by the java arrays class. Then we will discuss a few important ones in detail.
|binary search()||It searches for an element contained in the sorted array by using Binary Search Algorithm.|
|asList()||It is used to convert an array to a list of elements.|
|binarySearch(array, fromIndex, toIndex, key, Comparator)||A range of specified arrays for the specified object is searched using the Binary Search Algorithm.|
|toString(original array)||A string representation of the contents of the array is returned. This representation consists of a list of the elements of the array enclosed in square brackets (). The elements are separated by a comma and a space and each element is converted to a string by the String. value of() function.|
|stream(original array)||A sequential stream will be returned with an array that is specified by its source. The stream is a sequence of objects represented as a channel of data that has a source where the data is situated, and a destination where it is transmitted.|
|spliterator(original array,fromIndex, endIndex )||A spliterator is returned which covers the range of the specified arrays. The Spliterator interface can be used for traversing and partitioning sequences.|
|spliterator(original array)||A spliterator covering all the elements of the array is returned.|
|sort(Ta,Comparator <super T>c)||The specified array of the objects according to the order which is induced by the comparator is sorted by this.|
|sort(originalArray, fromIndex, endIndex)||The specified range of the array is sorted in ascending order.|
|sort(Ta, int fromIndex, int toIndex,Comparator<super T>c)||The specified range of the specified array of objects according to the specified comparator is sorted.|
|sort(original array)||The entire array is sorted in ascending order|
|setAll(originalArray, functionalGenerator)||Sets the elements of the array using the generator function which is already provided.|
|parallel Sort(original array)||Sorts the concerned array using the parallel sort.|
|paralleSetAll(originalArray, functionalGenerator)||All elements are set into parallel by using the generator function.|
|parallelPrefix(originalArray, operator)||For a complete array it performs parallelPrefix function.|
|parallelPrefix(originalArray, fromIndex, endIndex, functionalOperator)||It performs parallelPrefix for the given range of the array with the specified functional operator.|
|mismatch(array1,array2)||It will search and return the index of the first unmatched element between the 2 concerned arrays.|
|hashCode(originalArray)||An integer hashCode of the array instance is returned. A hashcode is a unique integer that represents an object in Java.|
|equals (array1, array2)||Will check if both the concerned arrays are equal or not. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.|
|fill(originalArray, fillValue)||The fill value is assigned to each index of the arrays.|
|deepToString(Objecta)||A string representation is returned of the deep contents and details of the concerned array.|
|deepHashcode(Objecta)||This method will receive an array and compute hash code based on the deep content in an array and return it in an integer.|
|deepEquals(Objecta1, Objecta2)||It returns true only if the 2 concerned arrays are equal to one another.|
|copyOfRange(originalArray, fromIndex, endIndex)||The concerned range of the concerned array is copied into the new array.|
|copyOf(originalArray, newLength)||Copies the specified array, truncating or padding with the default value (if necessary) so the copy has the specified length.|
|compare(array 1, array2)||Two arrays that are passed as parameters lexicographically are compared to each other.|
The table covered all the methods of the java.util.Arrays. Now, we will discuss a few commonly used methods in more detail.
Implementation of Arrays Class in Java
asList (Original Array)
- a – array of objects from which we get our list.
- List<T> => A fixed-size list of a specified array.
Explanation In the example above, we use the asList method of the Arrays class. We declare an Integer array and then pass it to the asList method to obtain a list.
binarySearch (Array, fromIndex, toIndex, Key, Comparator) Method
- a: The array to be searched
- key: The value to be searched for
- int: index of the search key, if it is contained in the array; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
Explanation Here we sort the input array as we need a sorted array for our binarySearch method. Then we pass the array and the key to the binarySearch method. the index at which we find the key is displayed.
- If the input list is not sorted, the results are undefined.
- If there are duplicates, there is no guarantee which one will be found.
toString(Original Array) Method
- a: array whose string representation is required
- string: string representation of an array
Explanation Here we use the toString method that helps us to convert the array to a string. Hence, we take an integer array. Then we use the toString method, and the array is converted to the string representation that is displayed in the output.
copyOf (Original Array, newLength) Method
- original: the array that will be copied
- new length: length of our copied array
- A new array that is copied from the original and truncated with zeros depending on our specified length.
Explanation Here we use the copyOf method of the Arrays class and it copies the input array into a new one.
copyOfRange (Original Array, fromIndex, endIndex) Method
- original: array from which values in the range will be copied
- from: first index of our range (inclusive)
- to: the last index of our range (exclusive)
Return Value: A new array that is copied from the original and truncated with zeros depending on our specified length.
Explanation Here we use the copyOfRange and specify a range from 2 to 4 and thus, the output shows the array of two elements.
equals (array1, array2) Method
- a1: the first array that will be tested for equality
- a2: the second array that will be tested for equality
- Returns true only if both arrays are equal. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.
Explanation Here we use the equals method and we use two arrays and call the equals method to check if they are equal or not. Since they aren't equal we get false as our result.
fill (Original Array, fillValue) Method
- a: array that will be filled.
- val: value that will be filled in all places of the array.
Explanation This example shows the basic usage of the 'fill' method. We fill our entire array with a key-value and here the value is 23. Hence the output received is an array with all the values as 23.
sort (Original Array) Method
Parameters: a: array that is to be sorted.
Explanation Here we use an array and call the sort method to arrange the elements of the array in ascending order i.e. sorting the array. Hence we get the sorted array as our output.
hashCode (Original Array) Method
- a: array whose hashcode will be computed.
- int: Hashcode of the array, a hashcode is a unique integer that represents an object in Java.
Explanation Here we use the 'hashCode' method and it helps us to compute the hashcode for the array that we pass in the argument.
deepEquals (Object a1, Object a2) Method
- a1: the array that is to be tested for equality.
- a2: the other array that is to be tested for equality.
- Returns true if both the arrays are equal, else false.
Explanation Here we use the deepEquals method and the output we receive is false because both the arrays aren't equal to each other.
Now that we have understood the implementation of these methods, let's take a look at the benefits of the Arrays class in Java.
Benefits of Arrays Class in Java
- Arrays class makes it easier to perform common operations on an array.
- No need to use complicated loops to work with an array.
- No need to reinvent the wheel for operations such as binary search and sorting.
Here's a quick summary of all that we have dealt with in the article.
- java.util.Arrays are a class that belongs to java.util package.
- Arrays class consists of static methods that make it easier to work with an array.
- The static methods of the Java Array class could be used to perform operations like
- filling the elements (fill(originalArray, fillValue))
- sorting the elements (sort(originalArray, fromIndex, endIndex))
- searching for the elements (binaySearch())
- converting the array elements to String (toString(original array))
- Many more…
- We can use these methods as follows: Arrays.<function name>;
Q: What is the java.util array?
A: java.util.arrays is a class that belongs to the java.util package. This class provides us with various methods which can be used with arrays and their types. For example: sort(), binarySearch(), equals() etc.These class methods can be used to manipulate the arrays efficiently.
Q: What does Arrays.sort () method do in Java?
A: The Arrays.sort () method allows us to sort the elements of the array depending on the comparator. The array has a lot of overloads which when in use can perform sorting in Java It has different overloads for sorting different primitive data types.
Q: Which sorting is used in Arrays.sort() in Java?
A: Arrays.sort uses dual-pivot Quicksort on primitives. It offers O(nlog(n)) performance and is typically faster than traditional (one-pivot) Quicksort implementations. However, it uses a stable, adaptive, iterative implementation of the mergesort algorithm for Array of Objects.
Q: What are collections and arrays classes?
A: Collections are generally dynamic(capable of action ) in nature and the class Collections help us with direct methods that act upon the collections. Arrays can be said to be static and they have class Arrays that provide us with methods that can be used to manipulate arrays. But we can not term these as direct methods i.e. Array objects can't invoke these methods. Rather, array objects need to be passed as an argument to these methods
Q: Is array an object in Java?
A: In Java programming language, arrays are objects and these objects are dynamically created and may be assigned to variables of type Object. All methods of class Object may be invoked on an array.