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:

List<String> listString = Arrays.asList("One", "Two", "Three");
listString.add("Four");	// throws UnsupportedOperationException
Returning a list of Integer objects:

List<Integer> listIntegers = Arrays.asList(1, 2, 3, 4, 5, 6);
Returning a list of Number objects:

List<Number> listNumbers = Arrays.asList(200, 30.24f, 6420.184d, 500);
Returning a list of Double objects:

List<Double> listDoubles = Arrays.asList(98.88, 99.99, 100.98);
 

2. Sorting Arrays



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:

int[] integers = {30, 57, 88, 12, 34, 54, 90, 62, 82, 10};

System.out.println("Before sort: " + Arrays.toString(integers));

Arrays.sort(integers);

System.out.println("After sort: " + Arrays.toString(integers));
Note that we use the Arrays.toString(array) method to print the content of the array in readable format.

Output:

Before sort: [30, 57, 88, 12, 34, 54, 90, 62, 82, 10]
After sort: [10, 12, 30, 34, 54, 57, 62, 82, 88, 90]
Using another overload, the following sorts a half of an array of float numbers:

float[] floats = {12.33f, 0.54f, 4.98f, 220.68f, 10.10f, 19.99f, 25.55f, 20.32f};

System.out.println("Before sort: " + Arrays.toString(floats));

Arrays.sort(floats, 0, 3);

System.out.println("After sort: " + Arrays.toString(floats));
 

The following code snippet sorts an array of String objects (the natural ordering of Strings is the alphabetic order):

String[] names = {"Carol", "Bob", "Alice", "John", "Tim", "Kate", "Mary"};

System.out.println("Before sort: " + Arrays.toString(names));

Arrays.sort(names);

System.out.println("After sort: " + Arrays.toString(names));
Output:

Before sort: [Carol, Bob, Alice, John, Tim, Kate, Mary]
After sort: [Alice, Bob, Carol, John, Kate, Mary, Tim]
For full examples of sorting arrays, see: Sorting Arrays Examples (with Comparable and Comparator)

 

3. Searching in Arrays

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:

int[] integers = {30, 57, 88, 12, 34, 54, 90, 62, 82, 10};

Arrays.sort(integers);

System.out.println("Array sorted: " + Arrays.toString(integers));

int foundIndex = Arrays.binarySearch(integers, 34);

System.out.println("Found 34 at index: " + foundIndex);
Output:

Array sorted: [10, 12, 30, 34, 54, 57, 62, 82, 88, 90]
Found 34 at index: 3
The following example illustrates searching an element in an array of String objects:

String[] names = {"Carol", "Bob", "Alice", "John", "Tim", "Kate", "Mary"};

Arrays.sort(names);

System.out.println("Array sorted: " + Arrays.toString(names));

int foundIndex = Arrays.binarySearch(names, "Mary");

System.out.println("Mary found at: " + foundIndex);
Output:

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)
 

References:

 

Related Java Arrays Tutorials:

 

Other Java Collections Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (ArraysUtilExamples1.java)ArraysUtilExamples1.java[Java Arrays Utilitly Examples]4 kB

Add comment