| 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
|
|
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.
|
 |
 |
|
|
subject: TreeMap uses compare/compareTo
|
|
|