Last Updated on 11 April 2024   |   Print Email
This Java tutorial helps you understand and use the Arrays utitlity class in the Java Collections framework.The java.util.Arrays class provides convenient methods for manipulating arrays such as sorting and searching. It also contains a useful method for converting an array to a List collection. In this article, we’re going to help you understand all the functionalities provided by the Arrays class with full code examples.Let’s explore in details.
1. Array to List view
The Arrays.asList(T… a) is a convenient method that converts the specified array to a List collection (an implementation of AbstractList). The returned list is a fixed-size list backed by the specified array. Any attempt to modify the returned list will result in an UnsuportedOperationException. For example:
The Arrays class provides several overloads that sort arrays of primitives into ascending order, arrays of Objects by natural ordering or by a specified comparator. We can either sort the full array or a range within the array. Here’s the list of sorting methods:
void sort(X[] a)
void sort(X[] a, int fromIndex, int toIndex)
void sort(T[] a, Comparator<? super T> c)
void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)
Here, X denotes a primitive type (byte, char, short, int, long, float and double); T denotes any reference type.The following example shows how to sort an array of integer numbers:
The Arrays class provides convenient methods for searching a specified element in an array using binary search algorithm. That means the array must be sorted (using Arrays.sort()) before it is searchable. Here’s the list of search methods:
int binarySearch(X[] a, X key)
int binarySearch(X[] a, int fromIndex, int toIndex, X key)
int binarySearch(Object[] a, Object key)
int binarySearch(Object[] a, int fromIndex, int toIndex, Object key)
int binarySearch(T[] a, T key, Comparator<? super T> c)
int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)
Here, X denotes a primitive type (byte, char, short, int, long, float and double); T denotes any reference type. All the search methods return an integer number indicating the index of the search key, if it is contained in the array. Otherwise it is a negative number. Note that the return value >=0 if and only if the key is found.Let’s see some code examples.The code snippet below searches for a number in an array of integers:
Array sorted: [Alice, Bob, Carol, John, Kate, Mary, Tim]
Mary found at: 5
For arrays of custom reference type, the following example illustrates searching for an Employee object in an array:
Employee[] employees = new Employee[5];
employees[0] = new Employee("Carol", 52000);
employees[1] = new Employee("Bob", 56000);
employees[2] = new Employee("Alice", 40000);
employees[3] = new Employee("John", 60000);
employees[4] = new Employee("Tim", 50000);
Arrays.sort(employees);
System.out.println("Employees sorted: " + Arrays.toString(employees));
Employee employeeToFind = new Employee("Carol");
foundIndex = Arrays.binarySearch(employees, employeeToFind);
if (foundIndex >= 0) {
System.out.println("Found Carol at index: " + foundIndex);
}
With the Employee class is written as follows:
class Employee implements Comparable<Employee> {
String name;
int salary;
Employee(String name) {
this.name = name;
}
Employee(int salary) {
this.salary = salary;
}
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
public int compareTo(Employee another) {
return this.name.compareTo(another.name);
}
public String toString() {
return this.name + " (" + salary + ")";
}
}
Output of the above code:
Employees sorted: [Alice (40000), Bob (56000), Carol (52000), John (60000), Tim (50000)]
Found Carol at index: 2
To illustrate searching with a comparator, the following example shows how to search an employee who earns a specified amount of salary:
Employee[] employees = new Employee[5];
employees[0] = new Employee("Carol", 52000);
employees[1] = new Employee("Bob", 56000);
employees[2] = new Employee("Alice", 40000);
employees[3] = new Employee("John", 60000);
employees[4] = new Employee("Tim", 50000);
Arrays.sort(employees);
System.out.println("Employees sorted: " + Arrays.toString(employees));
Employee employeeToFind = new Employee(60000);
int foundIndex = Arrays.binarySearch(employees, employeeToFind, new EmployeeComparator());
if (foundIndex >= 0) {
employeeToFind = employees[foundIndex];
System.out.println("Found 60,000 earner: " + employeeToFind);
}
Given the following comparator class:
class EmployeeComparator implements Comparator<Employee> {
public int compare(Employee emp1, Employee emp2) {
return new Integer(emp1.salary).compareTo(emp2.salary);
}
}
then the above code produces the following output:
Employees sorted: [Alice (40000), Bob (56000), Carol (52000), John (60000), Tim (50000)]
Found 60,000 earner: John (60000)
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments