Reputation: 3
I have been having some trouble using the function containsKey. I wrote a small program to show where I am expecting containsKey to give me a different result:
HashMap<IdentifierInterface, Set<NaturalNumberInterface>> hashMap;
HashMap<StringBuffer, Integer> works;
TryHashmap(){
hashMap = new HashMap<IdentifierInterface, Set<NaturalNumberInterface>>();
works = new HashMap<StringBuffer, Integer>();
}
private void start() {
Identifier iden = new Identifier('a');
NaturalNumber nn = new NaturalNumber('8');
Set<NaturalNumberInterface> set = new Set<NaturalNumberInterface>();
set.insert(nn);
hashMap.put(iden, set);
System.out.println(hashMap.containsKey(iden));
Identifier newIden = new Identifier('a');
System.out.println(hashMap.containsKey(newIden)); //TODO why is this not true?
iden.init('g');
System.out.println(hashMap.containsKey(iden));
}
public static void main(String[] argv) {
new TryHashmap().start();
}
The constructor of the Identifier class is as follows, the init() is similar but it will remove anything that was in the identifier before.
Identifier(char c){
iden = new StringBuffer();
iden.append(c);
}
I put something into the hashmap using an Identifier as key, but when I try to use an Identifier with a different name but with the same content the containsKey function returns false where I am expecting a true. (the output prints true false true)
Thanks in advance!
Upvotes: 0
Views: 1974
Reputation: 78
method containsKey
in HashMap.class
/**
* Returns <tt>true</tt> if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
*/
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
method getEntry
in HashMap.class
/**
* Returns the entry associated with the specified key in the
* HashMap. Returns null if the HashMap contains no mapping
* for the key.
*/
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
the method getEntry
told us that the result will be true
, only if the Object a
has the same hashCode()
as the Object b
and a.equals(b)
Upvotes: 0
Reputation: 809
Implement equals()
and hashCode()
for the identifier object. hashCode
is needed to find the relevant bucket and equals
is required to handle collisions while hashing.
Upvotes: 1