Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparable and Collections.sort()

 
Shawn Smith
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never mind, I'm a moron.

Amazing how much != and == look alike after a few hours of coding....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic