I am looking for advice, because I get an error when I run the following code:
public class Test9 {
public static void main(String[] args) {
Object [] myObjects = {
new Integer(12),
new String("foo"),
new Integer(5),
new Boolean(true)
};
Arrays.sort(myObjects);
for(int i=0; i<myObjects.length; i++) {
System.out.print(myObjects[i].toString());
//System.out.print(" ");
}
}
}
The error I am getting is:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at java.lang.Integer.compareTo(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at Practicequestions.Test9.main(Test9.java:18)
This a generic type array. So when you trying to sort it with
public static void sort(Object[] a)it populate runtime ClassCastException cause array contains elements that are not mutually comparable.Array.sort() specified array of objects into ascending order, according to the natural ordering of its elements.
There is a another method you can use it
sort(Object[] a,Comparator c). Implement Comparator with your own logic and pass it.