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

I have a HashMap 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


it returns false. Why is that?


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.




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: