javacollections

How contains method of Set collection works


Hi I am new to java as i know Set collection doesn't take duplicate and its contains method should return true when element is already present in collection. I am trying to run below program but I am getting unexpected result.

public class UserDefinedName {
    private final String first, last;

    public UserDefinedName(String first, String last) {
        this.first = first;
        this.last = last;
    }

    public boolean equals(Object o) {
        if (!(o instanceof UserDefinedName))
            return false;
        UserDefinedName n = (UserDefinedName) o;
        return n.first.equals(first) && n.last.equals(last);
    }

    public static void main(String[] args) {
        Set<UserDefinedName> s = new HashSet<UserDefinedName>();
        s.add(new UserDefinedName("Carballo", "Videl"));
        System.out.println(s.contains(new UserDefinedName("Carballo", "Videl")));
    }
}

I am expecting in the output true but program prints false. what I am doing wrong?


Solution

  • From the Object javadoc

    If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

    If the hashCode() method is not overridden then the Object's hashCode() method is used which is default implementation.

    In your case you had overridden the equals method but you use the default implementation of the hashCode() as you didn't override the hashCode() method in your UserDefinedName class.

    The UserDefinedName class overrides the equals method, and the hashCode contract demands that equal objects have equal hash codes. To fulfill this contract, you must override hashCode whenever you override equals

    add following code and it will work.

    public int hashCode() {
        return 37 * first.hashCode() + last.hashCode(); 
    }