How to sort elements in Object Array in Java?
Declaration :
|
1 |
public static void sort(Object[] a) |
Explanation :
| Purpose | The java.util.Arrays.sort(Object[]) method sorts the specified array of Objects into ascending order according to the natural ordering of its elements. |
| Parameters | a ===> This is the array to be sorted. |
| Return Value | This method does not return any value. |
| Exception | ClassCastException — if the array contains elements that are not mutually comparable (for example strings and integers). |
Java Program : Example
Below example will explain java.util.Arrays.sort() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.c4learn; import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // Initialize unsorted Object array Object obj[] = { 30, 10, 20 }; // Print the Unsorted Array List System.out.println("The unsorted object array is:"); for (Object num : obj) { System.out.println("Array Element is " + num); } // Sort the array Arrays.sort(obj); // Print the Sorted Array List System.out.println("The sorted Object array is:"); for (Object num : obj) { System.out.println("Array Element is " + num); } } } |
Output of Program :
|
1 2 3 4 5 6 7 8 |
The unsorted object array is: Array Element is 30 Array Element is 10 Array Element is 20 The sorted Object array is: Array Element is 10 Array Element is 20 Array Element is 30 |
