Arrays Class in Java
Arrays Class has built in functions to achieve the frequently used array operations.
These include :
– asList() for creating a List from the array
– sort() for sorting arrays
– binarySearch() for searching a sorted array
– equals() for comparing arrays
– fill() for filling values into an array
Let’s see some examples of these methods.
Arrays asList()
Arrays.asList() returns a fixed-size list backed by the specified array.
List<String> employees = Arrays.asList("John", "Larry", "Bob"); for(String emp : employees){ System.out.println(emp); }
Output:
John
Larry
Bob
Arrays sort() for sorting arrays
Arrays sort() method sorts the specified array in ascending order.
int[] numbers = { 23, 11, 5, 42, 3, 13 }; Arrays.sort(numbers); for (int number : numbers) System.out.println(number);
Output:
3
5
11
13
23
42
We can also pass a Comparator to the sort method for sorting in custom order.
String[] names = { "John", "Larry", "Bob" }; Arrays.sort(names, new Comparator<String>() { @Override public int compare(String o1, String o2) { // TODO Auto-generated method stub return o2.compareTo(o1); } }); for (String name : names) System.out.println(name);
Output:
Larry
John
Bob
Arrays binarySearch()
This method searches the specified array for the specified value using the binary search algorithm.
The array must be sorted prior to making this call. If it is not sorted, the results are undefined.
int location = Arrays.binarySearch(numbers, 13); if (location >= 0) System.out.println("13 is found at location = " + location); else System.out.println("13 not found in numbers array"); location = Arrays.binarySearch(numbers, 14); if (location >= 0) System.out.println("14 is found at location = " + location); else System.out.println("14 not found in numbers array");
Output:
13 is found at location = 3
14 not found in numbers array
Arrays equals()
This method returns true if both arrays contain the same elements in the same order
int[] copyNumbers = new int[numbers.length]; System.arraycopy(numbers, 0, copyNumbers, 0, numbers.length); System.out.println("Comparing the arrays numbers and copyNumbers returns : " + Arrays.equals(numbers, copyNumbers));
Output:
Comparing the arrays numbers and copyNumbers returns : true
Arrays fill()
This method assigns the specified boolean value to each element of the specified range
int[] arrayOfNineOnes = new int[10]; Arrays.fill(arrayOfNineOnes, 1); for (int elem : arrayOfNineOnes) System.out.print(elem + " ");
Output:
1 1 1 1 1 1 1 1 1 1
You may also like the following articles :
- TopJavaTutorial Magazine : August 2016
- Top 10 Java Collection articles
- Top 10 sorting algorithms in Java
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post