tags:

views:

1051

answers:

5

My first instinct is to say each key is an object, and has a hash code, which is what is used to determine if a duplicate is being inserted. However, I can't find anything to back that up for sure. Can someone provide a link that says that, or provide the real answer here? Thanks!

A: 

It uses the equals() method on the key. The hashCode() method just helps efficiently store the keys for the map.

Marc Novakowski
+3  A: 

Read the question wrong, but the person's answer above is correct and my link provides the answer as to how it is determined (the equals method). Look at the contains and get methods in the link.

How a map inserts: There cannot be a duplicate key in a Map. It will replace the old value with the new value if you find a duplicate key. Here is a link to the Map Interface. In addition, if you look at the put(K key, V value) method, it also explains how a map works. Hope that helps.

daub815
+13  A: 

The Map interface specifies that if two keys are null they are duplicates, otherwise if there's a key k such that key.equals(k), then there is a duplicate. See the contains or get method here:

http://java.sun.com/javase/6/docs/api/java/util/Map.html#containsKey(java.lang.Object)

However, it's up to the Map implementation how to go about performing that check, and a HashMap will use a hash code to narrow the potential keys it will check with the equals method. So in practice, for a typical hash based map, to check for duplicates a map will take the hashcode (probably mod some size), and use equals to compare against any keys whose hashcode mod the same size gives the same remainder.

Dave L.
Thanks for explaining it much better than I :)
daub815
+1  A: 

I'm assuming you're referring to java.util.Map, which is an interface provided in the standard Java libraries. The method of determining if a key is duplicate is left up to the specific implementation. A java.util.HashMap uses equals and hashCode, for example. You can write your own implementation of Map that uses something totally different.

Apocalisp
A: 

Careful on an edge case here. Null keys are not always duplicates. In fact, null keys turn out to be out to cause much frustration inbetween Map implementations (see my post on Consistency).

For example null keys are OK in HashMaps, but not in a TreeMap that uses natural ordering, or ConccurentHashMap where null keys are forbidden. The problem here is that they throw uncaught exceptions on many of their methods if you use a null key and that introduces scary run-time bugs when you switch implementations during refactoring.

Scanningcrew