java.util.Arrays sort(Object[] a)
Description
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort. The sort() method is overloaded in such a way that each primitive data type is handled. On this example we will be showing the sorting of array of Objects.
Notes:
- This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.
- This method will throw ClassCastException if the array contains elements that are not mutually comparable (for example, strings and integers).
- This method will yield the same result as sort(Object[] a, int fromIndex, int toIndex) method on such cases that the fromIndex is 0 and endIndex is equal to length. In short Arrays.sort(Object[] a) is equals to Arrays.sort(Object[] a, 0,a.length).
Method Syntax
public static void sort(Object[] a)
Method Argument
Data Type | Parameter | Description |
---|---|---|
Object[] | a | the array to be sorted |
Method Returns
The sort(int[] a) method returns void.
Compatibility
Requires Java 1.2 and up
Java Arrays sort(Object[] a) Example
Below is a java code demonstrates the use of sort(Object[] a) method of Arrays class. The example presented might be simple however it shows the behaviour of the sort(Object[] a) method.
package com.javatutorialhq.java.examples; import java.util.Arrays; /* * A java example source code to demonstrate * the use of sort(Object[] a) method of Arrays class */ public class ArraysSortObjectExample { public static void main(String[] args) { // initialize a new Object array Object[] a = new Object[]{"Test", "String", "123", "Ab", "AB", "A2", "A1"}; // print the contents of array of Objects System.out.println("Original:"+Arrays.toString(a)); // sort our array of Objects in ascending order Arrays.sort(a); // print the sorted array of Objects System.out.println("Sorted:"+Arrays.toString(a)); } }
The above java example source code demonstrates the use of sort(Object[] a) method of Arrays class. We simply declare a new array of Objects and we printed the values using the toString() method of Arrays class. Then we sorted the Object array using the sort() method and the sorted values were also printed the same way as what we did on the original/unsorted array.