This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes TreeMap uses compare/compareTo Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "TreeMap uses compare/compareTo" Watch "TreeMap uses compare/compareTo" New topic
Author

TreeMap uses compare/compareTo

Douglas Boff Nandi
Ranch Hand

Joined: Feb 25, 2008
Posts: 34
Given the following code:



Why the output is
{a=c}
{a=c}
?
The code uses compareTo to define if a key already exists in the map? Can anyone explain this? Thank you all
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16690
    
  19

The code uses compareTo to define if a key already exists in the map? Can anyone explain this? Thank you all


The purpose of the compareTo() is to report if two objects are less than, greater than, or equal -- in this example, the objects are always equal. Meaning besides the first key, adding any key will report that the key is already in the map.

Now... here the relevant quote for the put() method....

put
public V put(K key, V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for this key, the old value is replaced.


So, first, you put {a=a} into the map. Then when you try to put {b=b} into the map, it will determine that the "b" key is already in the map (because it is equal to the "a" key) and replace the value, resulting in {a=b}. Finally, the same thing happens when you try to put {c=c} into the map, resulting in {a=c}.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Douglas Boff Nandi
Ranch Hand

Joined: Feb 25, 2008
Posts: 34
Thank you! Now its clear for me.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: TreeMap uses compare/compareTo
 
Similar Threads
Why will TreeMap<K,V>(Comparator) not compile?
Discussing errata for K&B, SCJP 6
K&B chapter 7 Q7 question HashMap vs TreeMap
why CompareTo exists when we already have equals method
Sorting a HasMap by Values