6

After adding two identical objects to a Set, I would expect the set to contain only one element.

public void addIdenticalObjectsToSet(){
    Set<Foo> set = new HashSet<Foo>();
    set.add(new Foo("totoro"));
    set.add(new Foo("totoro"));
    Assert.assertEquals(1, set.size());            // PROBLEM: SIZE=2
}

private class Foo {
    private String id;
    public Foo(String id) {
        this.id = id;
    }
    public String getId() {
        return id;
    }
    public boolean equals(Object obj) {
        return obj!= null && obj instanceof Foo &&
            ((Foo)obj).getId().equals(this.getId());
    }
    public int hashcode() {
        return this.getId().hashCode();
    }
}

I consider two objects as identical if they have the same id (String).

Other strange thing: Neither Foo.equals nor Foo.hashcode are accessed, as far as I can tell using debug/breakpoints. What am I missing?

2
  • 2
    try to use @Override anotation Commented Jan 6, 2012 at 8:23
  • 2
    Try applying @Override on the methods which you think are overridden Commented Jan 6, 2012 at 8:24

1 Answer 1

15
public int hashcode() {
        return this.getId().hashCode();
    }

should be

@Override
public int hashCode() {
        return this.getId().hashCode();
    }

The annotation would have told you about the spelling mistake.

There should also be a (missing) little triangle symbol in your IDE on the method to indicate if an interface is being implemented or a parent method overridden.

Sign up to request clarification or add additional context in comments.

2 Comments

+1: Similar to using compareto instead of compareTo. There is a hashcode method in the Java 6 JDK ;)
I think FindBugs would also have caught this. Something about implementing equals but not hashCode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.