-2

got stuck on the test tusk:

 class MyKeys {
 Integer key;
 MyKeys(Integer k) {
 key = k;
 }
 public boolean equals(Object o) {
 return ((MyKeys) o).key == this.key;
 }
}

And this code snippet:

Map m = new HashMap();
MyKeys m1 = new MyKeys(1);
MyKeys m2 = new MyKeys(2);
MyKeys m3 = new MyKeys(1);
MyKeys m4 = new MyKeys(new Integer(2));
m.put(m1, "car");
m.put(m2, "boat");
m.put(m3, "plane");
m.put(m4, "bus");
System.out.print(m.size()); 

So, my expected output would be "2", while it's actually 4. I guess there is some problem with correctness of overriding equals method. Any help is useful.

tarmogoyf
  • 298
  • 3
  • 17
  • What confuses me more, is that SOUT m1.equals(m3) shows "true". – tarmogoyf Feb 04 '19 at 14:36
  • 1
    1. You didn't override `hashCode`. 2. You compared `Integer`s with == instead of equals. – Eran Feb 04 '19 at 14:36
  • Yes, I *think* what's going on is the hash code. Each of those hashes to a different value, so they each get stored individually. Hence, the size is 4, for 4 objects. – markspace Feb 04 '19 at 14:38
  • Also, if the OP didn't know about the the pitfalls in that suggested duplicate link, then get a copy of *Effective Java* by Joushua Bloch. Lots of useful advice in that book. – markspace Feb 04 '19 at 14:40
  • 1
    Unrelated: in `equals` check if `o` is null and if it's an instance of `MyKey` – jhamon Feb 04 '19 at 14:40

1 Answers1

1

You have to compare the object's key by using ".equals()" instead of "==". You also need to implement the hashCode() as required.

Mick
  • 954
  • 7
  • 17