utkarsh shukla utkarsh shukla - 1 year ago 50
Java Question

Is there any internal mapping of an object's hashcode to what we override in our classes

Sets care about uniqueness, so while implementing set in our program we must override the

method, so that we do not end up with duplicates. A reference holds its validity within the context of the single and current instance of the JVM, keeping this in mind I tried to code my program this way. Within
(lines 4-6). I have tried to put my query in a practical way by using comments in those lines.

class TestCase {
transient private int x;
private int y;
public TestCase(int x, int y) {
this.x = x;
this.y = y;
public boolean equals(Object o) {
if (o instanceof TestCase && (((TestCase) o).getXValue() == getYValue()))
return true;
return false;
public int hashCode() {
return x + y;
public int getXValue() {
return x;
public int getYValue() {
return y;

class TestSet {
public static void main(String[] args) {
TestCase tc1 = new TestCase(4, 8);
TestCase tc2 = new TestCase(4, 8);
Set<TestCase> set = new HashSet<TestCase>();
System.out.println(set.add(tc2));//fails and gives us false.
tc2 = new TestCase(4, 8);
System.out.println(set.add(tc2));//succeeds and gives us true?

Answer Source

First you better fix or remove your equals method completely. Your situation has nothing to do with how hashCode method is working, I will explain how it works below:

// Set is looking for tc2 and finds object with same ref, because of previous set.add(tc2);
System.out.println(set.add(tc2));//fails and gives us false.

// You create new object with new reference.
tc2 = new TestCase(4, 8);

// Yes, because you changed tc2 variable and assigned new reference to it.
System.out.println(set.add(tc2));//succeeds and gives us true?