Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap containsKey() returns false although hashCode() and equals() are true

Tags:

java

hashmap

I have a HashMap<Vertex, Integer> called vertexIndexes. If I iterate through it with this code:

public boolean search(String vertexName){
    for (Vertex name: vertexIndexes.keySet()){        
        String key =   name.toString();
        String value = vertexIndexes.get(name).toString();              
        System.out.println(key + " " + value + " "+ (name.hashCode() == vertexName.hashCode()) + " " + name.equals(vertexName));  
    }
...
}

it produces this output:

Diessen 0 false false
Herrsching 5 false false
Schondorf 2 false false
Greifenberg 3 false false
Stegen 4 false false
Utting 1 false false
Andechs 6 false false
Fischen 7 true true

So you can see, that the Vertex Fischen is present and the hashCode and equals methods work fine. But if I run

vertexIndexes.containsKey("Fischen")

it returns false.

Why is that? I lose my mind over it.

like image 576
gutenmorgenuhu Avatar asked Mar 26 '19 10:03

gutenmorgenuhu


Video Answer


1 Answers

name.equals(vertexName) compares a Vertex to a String. While your Vertex class equals method might return true when you pass a String to it, String's equals will never return true when you pass a Vertex to it.

HashMap probably tests whether vertexName.equals(name), which returns false.

Change

vertexIndexes.containsKey("Fischen")

to

vertexIndexes.containsKey(new Vertex("Fischen"))

or change the key of your Map to String.

BTW, you could have avoided that issue in the first place if you followed the contract of the equals method that appears in the Javadoc of the Object class:

• It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

Your equals implementation is not symmetric.

like image 95
Eran Avatar answered Nov 17 '22 08:11

Eran