What will be displayed ?

public class Tst {
    public static class Foo {
        private final Integer x;

        public Foo(Integer x) {
            this.x = x;
        }

        public boolean equals(Foo f) {
            return f.x.equals(this.x);
        }

        public int hashCode() {
            return x.intValue();
        }
    }
    public static void main(String[] args) {
        final Foo f1 = new Foo(1);
        final Foo f2 = new Foo(1);

        final Set<Foo> set = new HashSet<Foo>();
        set.add(f1);
        set.add(f2);

        System.out.println(set.size());
    }
}
Explanation
It is not easy to spot a mistake in the definition of equals method which has to be equals(Object f) instead of equals(Foo f)
Set class uses equals(Object o) for comparison, which in this case will return false.
This mistake was one of the reasons to introduce the @Override annotation

Мобильное приложение Beta

Get it on Google Play