The sort method can take a Comparator. Make a small class that implements that Interface. Inside this class, implement the compare method as you see fit. The simple way is to just return o1.toString().compareTo(o2.toString()) which would sort Integers and Strings but I'm not sure if it will sort the way you want... You would have to write more to get it to sort exactly how you want it. If you want to be able to sort ASC and DESC with the same comparator, you could have boolean flags that the compare method uses to do the ordering.
See http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html#compare(T, T)
By default Collections.sort sorts your list in "natural" order, that is when it compares two elements in the list to sort them it calls the compareTo method on one of them, with the other as an argument.
However there's no "natural" ordering between integers and strings. You have to decide for yourself how to compare the two. Is "A23" less than, or greater than 123 ? Which is greater 29 or "dog"?
In particular if you translate numbers to strings in order to compare you'll get 123 < 23 because the first character is lower.
Having decided how you want the items ordered you need to write your own Comparator class. This will have a method which compares two entries from the list and returns a negative, zero or positive number according to how your comparison works. Typically you'll use an anonymous class.
as in:
Collections.sort(mixedList, new Comparator() {
public int compare(Object item1, Object item2) {
if(item1 instanceof Integer) {
if(item2 instanceof Integer) {
return item1.compareTo(item2);
else if item2 instanceof String) {
... well this is up to you.
}
});
Hi Anish,
write your own comparator.
By the way how are you going to compare a string with an int?
I hope you assume both are string and int represent numbers.
Write a small utility method to do that.
the Class cast exception is obvious as you can not do the same comparision for both the int and string.
However try to make your program better by making sure that all entries are either ints or strings. That will be a better design and also save you from a lot of problems going forward.
Hope this helps.
Rgds.
Ayusman