aspose file tools*
The moose likes Java in General and the fly likes Comparable and Collections.sort() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Comparable and Collections.sort()" Watch "Comparable and Collections.sort()" New topic
Author

Comparable and Collections.sort()

Shawn Smith
Ranch Hand

Joined: Feb 22, 2011
Posts: 41
All,

I'm playing around with the sort method in collections and getting some behavior that isn't what I expect.

Inside a simple class that extends Comparable, I have a compareTo that looks like:



When I do a Collections.sort() on a list populated with this type, the results look very unsorted. I know compareTo is being called based on the debug output (below). Also in the debug you can see the previous sort (using a Comparator) which is the input List for the Comparable sort.

######### SORTED LIST (INT) ########
String: Hello Int: -3
String: World Int: -1
String: Hello Int: 2
String: Bar Int: 3
String: Foo Int: 100
String: Hello Int: 300
######### SORTED LIST (INT) ########

######### SORT BASED ON COMPARABLE INTERFACE ########
String compareTo resulted in -15
String compareTo resulted in 15
String compareTo resulted in 6
String compareTo resulted in -4
String compareTo resulted in -2
String: Hello Int: -3
String: World Int: -1
String: Hello Int: 2
String: Bar Int: 3
String: Foo Int: 100
String: Hello Int: 300
######### SORT BASED ON COMPARABLE INTERFACE ########

Any insight would be greatly appreciated.

Shawn
Shawn Smith
Ranch Hand

Joined: Feb 22, 2011
Posts: 41
Never mind, I'm a moron.

Amazing how much != and == look alike after a few hours of coding....
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Comparable and Collections.sort()