Java Arrays Class
In this tutorial, we will learn about the Arrays class from the Java Collection Framework. This class belongs to java.util
package and provides various methods to work with arrays and its type.
This class provides various methods like sort()
, binarySearch()
, equals()
, copyOf()
, fill()
etc to manipulate the arrays efficiently. We will discuss each method individually later in this tutorial. Let's look into the table given below, this table describes each method of Arrays class in a short. All the methods of this class can be called directly using the class name i.e. without creating an object.
Method
|
Description
|
static <T> List<T> asList(T... a)
|
This method returns a fixed-size list backed by the specified array.
|
static int binarySearch(byte[] a, byte key)
|
Searches the specified array of bytes for the specified value using the binary search algorithm.
|
static <T extends Comparable<? super T>> int compare(T[] a, T[] b)
|
Compares two Object arrays, within comparable elements, lexicographically.
|
static <T> int compare(T[] a, T[] b, Comparator<? super T> cmp)
|
Compares two Object arrays lexicographically using a specified comparator.
|
static int compareUnsigned?(short[] a, short[] b)
|
Compares two short arrays lexicographically, numerically treating elements as unsigned.
|
static <T> T[] copyOf(T[] original, int newLength)
|
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.
|
static <T,?U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType)
|
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.
|
static <T> T[] copyOfRange(T[] original, int from, int to)
|
Copies the specified range of the specified array into a new array.
|
static <T,?U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)
|
Copies the specified range of the specified array into a new array.
|
static boolean deepEquals(Object[] a1, Object[] a2)
|
This method returns true if the two specified arrays are deeply equal to one another.
|
static int deepHashCode(Object[] a)
|
This method returns a hash code based on the "deep contents" of the specified array.
|
static String deepToString(Object[] a)
|
This method returns a string representation of the "deep contents" of the specified array.
|
static <T> boolean equals(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)
|
This method returns true if the two specified arrays of Objects, over the specified ranges, are equal to one another.
|
static <T> boolean equals(T[] a, T[] a2, Comparator<? super T> cmp)
|
This method returns true if the two specified arrays of Objects are equal to one another.
|
static void fill(Object[] a, int fromIndex, int toIndex, Object val)
|
Assigns the specified Object reference to each element of the specified range of the specified array of Objects.
|
static void fill(Object[] a, Object val)
|
Assigns the specified Object reference to each element of the specified array of Objects.
|
static int hashCode(Object[] a)
|
This method returns a hash code based on the contents of the specified array.
|
static <T> int mismatch?(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)
|
Finds and returns the relative index of the first mismatch between two Object arrays over the specified ranges, otherwise return -1 if no mismatch is found.
|
static <T> int mismatch?(T[] a, T[] b, Comparator<? super T> cmp)
|
Finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found.
|
static <T> void parallelPrefix?(T[] array, int fromIndex, int toIndex, BinaryOperator<T> op)
|
Performs parallelPrefix(Object[], BinaryOperator) for the given subrange of the array.
|
static <T> void parallelPrefix?(T[] array, BinaryOperator<T> op)
|
Cumulates, in parallel, each element of the given array in place, using the supplied function.
|
static <T> void parallelSetAll?(T[] array, IntFunction<? extends T> generator)
|
Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
|
static <T> void parallelSort?(T[] a, int fromIndex, int toIndex, Comparator<? super T> cmp)
|
Sorts the specified range of the specified array of objects according to the order induced by the specified comparator.
|
static <T> void parallelSort?(T[] a, Comparator<? super T> cmp)
|
Sorts the specified array of objects according to the order induced by the specified comparator.
|
static <T> void setAll?(T[] array, IntFunction<? extends T> generator)
|
Set all elements of the specified array, using the provided generator function to compute each element.
|
static <T> void sort?(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)
|
Sorts the specified range of the specified array of objects according to the order induced by the specified comparator.
|
static <T> void sort?(T[] a, Comparator<? super T> c)
|
Sorts the specified array of objects according to the order induced by the specified comparator.
|
static <T> Spliterator<T> spliterator?(T[] array)
|
This method returns a Spliterator covering all of the specified array.
|
static <T> Spliterator<T> spliterator?(T[] array, int startInclusive, int endExclusive)
|
This method returns a Spliterator covering the specified range of the specified array.
|
static <T> Stream<T> stream?(T[] array)
|
This method returns a sequential Stream with the specified array as its source.
|
static <T> Stream<T> stream?(T[] array, int startInclusive, int endExclusive)
|
This method returns a sequential Stream with the specified range of the specified array as its source.
|
static String toString?(Object[] a)
|
This method returns a string representation of the contents of the specified array.
|
|
Example Sort Arrays
This example sorts a given array in ascending order. Using Arrays.sort()
method whatever the array we pass it will sort and output will be in a sorted manner. In the below code you can see array elements are not alphabetically sorted but in the output, all the array elements are in a sorted manner.
import java.util.Arrays;
public class StudyTonight
{
public static void main(String[] args)
{
String array[]={"elephant", "dog", "apple", "cat", "bat"};
Arrays.sort(array);
for (String str: array)
{
System.out.println(str);
}
}
}
apple
bat
cat
dog
elephant
Example: Search in Arrays
This example searches the index of a given number in an array using binary search. We will pass two parameters i.e. array and key to search and it will return the index of the key.
Binary search works only on sorted array so while calling this method makes sure that you have passed a sorted array as a parameter in the method.
import java.util.Arrays;
public class StudyTonight
{
public static void main(String[] args)
{
int array[]={2,6,7,8,13,19,27,55,80};
int key = 19;
System.out.print(key+" found at index: "+Arrays.binarySearch(array,key));
}
}
19 found at index: 5
Example Compare two Arrays
This example checks whether given arrays are equal or not. We pass two arrays in this method and it will return a boolean value true for equal arrays and false for unequal arrays. We can see in the given array both arrays unequal and so this method returned a false value.
import java.util.Arrays;
public class StudyTonight
{
public static void main(String[] args)
{
String array1[]={"Bangalore","Delhi", "Mumbai", "Kolkata"};
String array2[]={"Noida","Hyderabad", "Chennai", "Chandigarh"};
if(Arrays.equals(array1, array2))
{
System.out.println("Arrays are equal");
}
else
{
System.out.println("Arrays are not equal");
}
}
}
Arrays are not equal
Example: Create Copy of Arrays
This example copies all the data of a given array to another array. This method accepts two parameters one is an original array and another one is an array where we want to copy data of the original array. In the code given below, you can see when we are printing elements of both the array they are printing the same it means they both contain the same element.
import java.util.Arrays;
public class StudyTonight
{
public static void main(String[] args)
{
String array1[]={"Bangalore","Delhi", "Mumbai", "Kolkata"};
String array2[]=Arrays.copyOf(array1, 4);
System.out.println("Elements of Array 1");
for(String str:array1)
{
System.out.print(str+" ");
}
System.out.println("\n");
System.out.println("Elements of Array 2");
for(String str:array2)
{
System.out.print(str+" ");
}
}
}
Elements of Array 1
Bangalore Delhi Mumbai Kolkata
Elements of Array 2
Bangalore Delhi Mumbai Kolkata
Example: Fill Array with Specific Value
When it comes to assigning the same value to all the array elements then this fill()
method is very useful because it assigns the same value to all the array elements regardless of the size of an array. You can see in the below code we assigned all the array elements with value 15 and in the output, all the elements are 15.
import java.util.Arrays;
public class StudyTonight
{
public static void main(String[] args)
{
int array[]={1, 3, 4, 8, 2, 34};
Arrays.fill(array, 15);
for(int arr:array)
{
System.out.print(arr+" ");
}
}
}
15 15 15 15 15 15
Example: Get List from Array
This method returns the fixed-sized list from an array. In the code snippet given below, we have an array of strings, and using Arrays.asList()
method we converted that method to a list of strings.
import java.util.Arrays;
import java.util.List;
public class StudyTonight
{
public static void main(String[] args)
{
String arr[]= new String[] { "Java", "C", "C++", "Python" };
List<String> list = Arrays.asList(arr);
System.out.println("List: " + list);
}
}
List: [Java, C, C++, Python]
Conclusion
To manipulate array generally we do manual operations for sorting and searching but for large arrays, these methods are highly effective. sort()
, fill()
, copyOf()
and equals()
are the methods that very often used in the programming world and this class has made this stuff very easy for programmers.