I am trying to understand internal implementation of object == operator comparison to achieve a same behavior of String == for my user defined class object.
Below is my implementation logic.
1. Bean Class
package com.study.equals;
public class SomeBean {
int id;
public SomeBean(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof SomeBean) {
return this.id==((SomeBean)obj).id;
} else {
return false;
}
}
@Override
public int hashCode() {
return this.id + 2000;
}
@Override
public String toString() {
return "[Inside toString: " + this.hashCode() + "]";
}
}
2. Test Class
package com.study.equals;
public class Test {
public static void main(String[] args) {
SomeBean obj1 = new SomeBean(10);
SomeBean obj2 = new SomeBean(10);
if(obj1 == obj2) {
System.out.println("true");
}else {
System.out.println("false");
}
}
}
- Expected output: true
- Actual output: false
Doubt
- Can someone help me to understand why I am getting false here?
- How can I get true as response here.