Arrays.sort(Object[]) in Java

Arrays.sort(Object[]): This method is available in java.util.Arrays class of Java.

Syntax:

void java.util.Arrays.sort(Object[] a)

This method takes one argument of type Object array as its parameter. This method sorts the specified array of objects into ascending order, according to the natural ordering of its elements.

Parameters: One parameter is required for this method.

a: the array to be sorted.

Throws:

1. ClassCastException - if the array contains elements that are not mutually comparable.

2. IllegalArgumentException - if the natural ordering of the array elements is found to violate the Comparable contract

Approach 1: When no exceptions

Java

import java.util.Arrays;

public class ArrayssortObject {
    public static void main(String[] args) {

        Object a[] = { 12, 6, 6, 2, 4, 56, 23 };

        Arrays.sort(a);
        System.out.println(Arrays.toString(a));
    }
}

Output:

[2, 4, 6, 6, 12, 23, 56]


Approach 2: ClassCastException

Java

import java.util.Arrays;

public class ArrayssortObject {
    public static void main(String[] args) {

        Object a[] = { 12, 6, 6, 'a', 4, 56, 23 };

        Arrays.sort(a);
        System.out.println(Arrays.toString(a));
    }
}

Output:

Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Character (java.lang.Integer and java.lang.Character are in module java.base of loader 'bootstrap') at java.base/java.lang.Character.compareTo(Character.java:132) at java.base/java.util.ComparableTimSort.binarySort(ComparableTimSort.java:262) at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:189) at java.base/java.util.Arrays.sort(Arrays.java:1040)


No comments:

Post a Comment