Vijay Vijay - 8 days ago 6
Java Question

Java collection sorting

When i run the below code, Collection.sort(l) will throw below exception.


Exception in thread "main" java.lang.ClassCastException:
learning.CollectionSort cannot be cast to java.lang.Comparable


public class CollectionSort {
public static void main (String[] args){
List l = new ArrayList();
CollectionSort obj1 = new CollectionSort();
CollectionSort obj2 = new CollectionSort();
l.add(obj1);
l.add(obj2);
Collections.sort(l);
for (int i = 0; i < l.size(); i++){
System.out.println(l.get(i));
}
}
}


This is because we have to implement comparable or comparator for sorting custom objects. Normally we will have properties in an object which are used for sorting.

But in the above code, we have no properties in this class. So is possible to sort the above list? Please share your thoughts.

Answer

But in the above code, we have no properties in this class. So is possible to sort the above list?

Yes, you could write a Comparator that orders based on hash code (hashCode()) or string value (toString()), and use that to sort the list ...

Collections.sort(l, new MyComparator()).

But it is unclear would be gained by that, as the resulting orders have no particular meaning. Indeed, if you are free to choose whatever basis you wish for sorting, then why not sort the list elements by their index in the list? Then your list is always trivially sorted without invoking any methods.

Comments