Fredrick Norman
Fredrick Norman

Reputation: 67

Why is the size of this set 1 after adding 5 objects?

I'm trying to figure out why this code outputs 1:

import java.util.HashSet;
import java.util.Set;

public class Test {
    public static void main(String[] args) {
        Set<Foo> myFooSet= new HashSet<Foo>(); 
        myFooSet.add(new Foo(2));
        myFooSet.add(new Foo(1));
        myFooSet.add(new Foo(3));
        myFooSet.add(new Foo(3));
        myFooSet.add(new Foo(2));
        System.out.print(myFooSet.size());
    }
}
class Foo {
     Integer code;
     Foo(Integer c) {
         code= c;
     }
     public boolean equals(Foo f) {
         return false;
     }
     public boolean equals(Object f) {
         return true;
     }
     public int hashCode() {
         return 17;
     }
}

Upvotes: 6

Views: 1252

Answers (2)

Eran
Eran

Reputation: 393936

Your defined public boolean equals(Object f) and public int hashCode() methods in the Foo class that basically say all Foo instances are equal to each other, so only one instance of Foo can be added to any HashSet.

Therefore myFooSet.size() will return 1, regardless of the number of Foo elements you attempted to add to it (as long as you added at least one).

Note: your public boolean equals(Foo f) method is never used by HashSet, since HashSet only uses the equals method declared in Object class - public boolean equals(Object obj) - which you overrode to always return true.

Upvotes: 18

Ori Marko
Ori Marko

Reputation: 58812

Adding to @Eran answer, defining equals(Foo f) method isn't overriding the Object.equals(java.lang.Object) method being used when comparing, even if your Object is Foo

public boolean equals(Foo f) {

Isn't called in your code

Upvotes: 2

Related Questions