Why does this result in 1?

  • A+
Category:Languages

I'm trying to figure out why the output of this code results in 1?

The code is as follows:

importjava.util.HashSet; importjava.util.Set;  public class Test {     public static void main(String[] args) {         Set<Foo> myFooSet= newHashSet<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;      } } 

I was wondering why does this code result in 1?

some extraa details

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: