aspose file tools*
The moose likes Java in General and the fly likes TreeMap Insanity (or is that me?) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "TreeMap Insanity (or is that me?)" Watch "TreeMap Insanity (or is that me?)" New topic
Author

TreeMap Insanity (or is that me?)

Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695


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

Joined: Jan 30, 2002
Posts: 3451
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


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

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

Joined: Jan 30, 2000
Posts: 18671
So, problem solved now?


"I'm not back." - Bill Harding, Twister
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

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 ]
 
 
subject: TreeMap Insanity (or is that me?)