Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

TreeMap Insanity (or is that me?)

 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

My selectMap() method returns a TreeMap. I've confirmed that the keys are being placed into the TreeMap *in order* (not that that should matter). When I then retrieve the keySet and try to iterate over them, I find that their "natural order" seems to be wacky.

Starting at the bottom, read the numbers from right to left. (imagine you're reading them in a mirror)
01
11
1
2
21
etc...

The same thing happens when I try to get values() to get a Collection view. From the API:
But in fact, it's in the same order as shown above (only the output is the 'value' part of the TreeMap and not the key)


What is going on? Is the "natural order" of Strings (as implemented by String's default Comparator) like this?

I think not, but what else could be happening?
[ April 05, 2003: Message edited by: Mike Curwen ]
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mike,
Umm, very strange. I ran a test and got the expected ASCII sort:

Output:

I guess you've checked that your keys are for sure Strings. Also, could it be an encoding problem? Perhaps with an encoding that reads right to left.
Michael Morris
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's the full code:Two things of note here.
//2 The extra "" was in fact turning it back into a String. If I removed the "", then I'd get a sorted result in DESCENDING order.

The real problem.... //1 DUH! It's a HashMap again! This is the type of thing that happens a lot when you 'improve' code, right? (the method didn't used to take a boolean 'sorted' parameter).
[ April 06, 2003: Message edited by: Mike Curwen ]
[ April 06, 2003: Message edited by: Mike Curwen ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, problem solved now?
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup. I was checking at the top of my method to see if I should make a HashMap or TreeMap, but then later on (at //2) I go ahead and make it a HashMap.
[ April 06, 2003: Message edited by: Mike Curwen ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic