Discussion Locked

Question on Sorted in java in LinkedList

0 helpful
2 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

My question is why sort method in LinkedList can not sort String typ and integer typ in the same list. For example if we creat list of LinkedList with integer numbers and string names
The code
in the test class Iam using Java API
LinkedList list = new LikedList();
list.add(new Integer(1));
list.add("AAAAA");
list.add(new Integer(6));
list.add("BBBBB");

//then when we print them
System.out.print("List is :" + list);
this will be the result
List is : [1, AAAAA, 6, BBBBB]
but when we try to sort them
Collections.sort(list);
System.out.print("Sorted list is " + list);
the result will give me error, because sort method can not sort two diffrenet data typ in the same list
I want to know why that can not happen.... where is the exzatly problem in the sort method that make can not do this...why we can not compare name(string data typ) with number (integer data typ)
I will be greatful if any on e can help me and answer my question

2 replies

by ira_rudowsky

Probably due to the implicit call sort makes to compareTo which is different for Strings and Integers. Each compareTo expects objects of the same type. Java can not compare Integer to String as there is no such compareTo

by jslarochelle

It is not obvious to write a useful sort for mix types. Although this might have worked for "build-in" wrappers it is difficult to do for user defined classes. How do you compare a Circle and a Square class ? Designers of libraries have to draw the line somewhere. I suppose they decided that mix types was a good place to draw the line even though it still allows some pathological cases. You just happen to have found a case where it make sense to you but there are much more cases that don't make sense.
For your application just use the sort(List, Comparator) method and write your own Comparator.
JS

This discussion is closed to new replies.