• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Jeanne Boyarsky
  • Tim Cooke
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
Bartenders:

TreeMap key issue

 
Ranch Hand
Posts: 294
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 808
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 78664
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You could change to a Map<Integer, Foo>, or supply a Comparator<String> which doesn’t use asciibetical ordering.
 
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
I like you because you always keep good, crunchy cereal in your pantry. This tiny ad agrees:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic