0

The following map's first value should be overriden by third value but is is not. why?

import java.util.*;

class A
{

int a, b;
A(int a,int b) {
    this.a = a;
    this.b = b;
}

public boolean equals(A aa) {
    if(this.a == aa.a && this.b == aa.b) {
        return true;
    }
    return false;
}
public int hashCode() {
    return this.a-this.b;
}
}

main class

public class MyClass { // main class


public static void main(String args[]) { // main method

 Map<A,Character> map = new LinkedHashMap<>();


 map.put(new A(1,2),'a');   //first
 map.put(new A(1,3),'b');   //second
 map.put(new A(1,2),'v');   //third


 for(A a : map.keySet()) {
     System.out.println(a.a+" "+a.b+" "+map.get(a));
 }

}

}

the output by the code is :

1 2 a

1 3 b

1 2 v

Amit Karn
  • 5
  • 1
  • This question is not a duplicate of "Overriding the java equals() method - not working? ". Issue here is a creation of new object, with same values, in a map. – Sabina Orazem Apr 15 '20 at 16:51
  • When adding third A object, you're not overriding the existing map pair, but creating a new one, since you're creating a new A object with same values. Do something like this: A a1 = new A(1,2); map.put(a1, 'a'); map.put(new A(1,3),'b'; map.put(a1, 'v');; – Sabina Orazem Apr 15 '20 at 16:53

1 Answers1

4

You are overloading the equals method, not overriding it. The correct signature is equals(Object):

public boolean equals(Object o) {
    if (!(o instanceof A)) {
        return false;
    }
    A aa = (A) o;
    if(this.a == aa.a && this.b == aa.b) {
        return true;
    }
    return false;
}

A good way to avoid these bugs in the future is to annotate methods you attempt to override with the @Override annotation - the compiler will issue an error if you have the wrong signature, like you had here.

Mureinik
  • 297,002
  • 52
  • 306
  • 350