artaxerxe
artaxerxe

Reputation: 6411

contains() method in java.util.HashSet doesn't behave as i expected from it

This is the java main() method:



    public static void main(String[] args) {
        
        HashSet set = new HashSet();
        Mapper test = new Mapper("asd", 0);
        set.add(test);
        
        System.out.println(new Mapper("asd", 0).equals(test));
        System.out.println(set.contains(new Mapper("asd", 0)));
        
    }

and my Mapper class is :

class Mapper {

String word;
Integer counter;

Mapper (String word, Integer counter) {
    
    this.word = word;
    this.counter = counter;
    
}

public boolean equals(Object o) {
    
    if ((o instanceof Mapper) && (((Mapper)o).word == this.word)) {
        
        return true;
        
    }
    
    return false;
    
}

}

and the result is :

true

false

From HashSet specifications, at this method I read this : "Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)). "

So, can anyone explain me where i'm wrong? Or ...?

Thanks.

Upvotes: 0

Views: 2848

Answers (2)

Daniel Lubarov
Daniel Lubarov

Reputation: 7924

The hashCode contract says that if two objects are equal, they should have the same hash code. Collections like HashSet assume that this is upheld.

Object's implementations of equals and hashCode are based on addresses (or object IDs). If you override equals to do a content comparison, you should override hashCode to generate a hash based on content.

Upvotes: 1

Edwin Buck
Edwin Buck

Reputation: 70909

You need to implement a proper hashCode() function.

public int hashCode() {
  // equal items should return the same hashcode
}

The Java utilites java.util contain a lot of classes which rely on hashing. To allow one to override equals() as they see fit means that one must also properly override hashCode() to match.

A correct implementation of hashCode() would return the same hash for any two objects where equals() returns true. Hash related functions check the hashes for equality before checking to see if the objects equal (to resolve hash collisions).

Upvotes: 8

Related Questions