Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: After adding 2 identical objects to a Set, it contains the 2 elements

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?

like image 851
Nicolas Raoul Avatar asked Jan 06 '12 08:01

Nicolas Raoul


People also ask

Can set contains duplicate objects?

A Set is a Collection that cannot contain duplicate elements.

Can two objects have same reference in Java?

No, it never returns true unless you feed it the same exact object reference. The reason for it is that Java objects are not "embedded" in one another: there is a reference to B inside A , but it refers to a completely different object.

How do you add two objects in Java?

var result = first. add(second); Write a Number class with a constructor that takes an int. Write an add method that returns a new number object and you're good to go.


1 Answers

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.

like image 190
Thilo Avatar answered Sep 27 '22 23:09

Thilo