• Post Reply Bookmark Topic Watch Topic
  • New Topic

TreeMap key issue  RSS feed

 
Davie Lin
Ranch Hand
Posts: 294
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

I am implementing TreeMap and I have 2 String Keys one is "304000" and the other is "1026994". I thought the ordering of the key should be "304000", "1026994". But when I step through the debugger, I am seeing "1026994" as the first key. Can someone enlighten me please?

Thanks
 
dennis deems
Ranch Hand
Posts: 808
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The String comparison doesn't see two numerical values, one of which is larger. It sees two sequences of characters. It compares them, index by index. It sees that '1' comes before '3', so that element is placed ahead of the other in the sort.
 
Campbell Ritchie
Marshal
Posts: 56522
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could change to a Map<Integer, Foo>, or supply a Comparator<String> which doesn’t use asciibetical ordering.
 
sandy sean
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this you are taking keys as Strings not as Integers.

By default TreeMap use natural order of keys to sort them.

so Treemap will sort "304000" and "1026994" lexicographically in which 1 comes before 3.
so it sort 1026994 before 304000.

If you want 304000 before 1026994 either you can take keys as Integer as:

TreeMap<Integer,your_choice_for_value>

Or you can provide an instance of Comparator in constructor of TreeMap as:

TreeMap(Comparator<? super K> comparator)

to provide user defined criteria for sorting.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!