What is the difference between Collections.sort(list)
and Collections.sort(list,null)
I supposed both of them compared elements in the list in their natural order.
So I tried these two codes:
CODE 1:
List<Object> list=Arrays.asList("hello",123);
Collections.sort(list);
CODE 2:
List<Object> list=Arrays.asList("hello",123);
Collections.sort(list,null);
The latter compiles but former doesn't giving the expected compiler error that instances of class Object are not comparable. Why latter does not give compile time error.
EDIT: Based on the comment given below. I understand why latter doesn't give compile time error but on running it throws ClassCastException : String cannot be converted into Integer
. How it deduced that runtime objects are String and Integer because what I think
public static sort(List<Object> list) ---> Since list was of type object
{
// For instances of object in list call the compareTo method
}
}
These are two different methods in Collections
//here the elements in list should impl. Comparable
Collections.sort(list)
//here we need a Comparator object, (null is Comparator obj too)
Collections.sort(list, null)
Now comes to the question of runtime classcast problem.
Java converts your list into array to do the sort in background. If your Comparator
is null, java will cast the element to Comparable
to do sort. Fortunately, the two elements in your list both (String and Integer
) implemented Comparable
. so till here no Exception.
You have only two elements (2<7 7 is the insertionsort threshold) in your list, so java just simply do insertion sort. Take the Integer, and call the compareTo()
method with your string as parameter. Here java cast the parameter to Integer, so that it can compare. As you've seen, String
cannot be cast to Integer
, you got that Exception.