Java Object equals
Java Object equals
This post was migrated from Tistory. You can find the original here.
Object.equals
1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {
Test t = new Test("hi");
Test t2 = new Test("hi");
t.equals(t2);
}
static class Test {
String test;
Test(String test) {
this.test = test;
}
}
Every object’s ancestor is Object, and Object has an equals method.
If you create an object and don’t override equals yourself,
1
2
3
public boolean equals(Object obj) {
return (this == obj);
}
it behaves as shown above—an equals that only returns true when the reference addresses are the same.
1
2
3
4
5
6
7
String t3 = "hi";
String t4 = "hi";
t3.equals(t4);
Long t5 = 5L;
Long t6 = 5L;
t5.equals(t6);
String’s equals looks like this:
1
2
3
4
5
6
7
8
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
return (anObject instanceof String aString)
&& (!COMPACT_STRINGS || this.coder == aString.coder)
&& StringLatin1.equals(value, aString.value);
}
And Long’s equals looks like this:
1
2
3
4
5
6
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}
Wrapper classes override equals to compare values instead of the reference address we might otherwise expect.
Conclusion
If you want to compare values rather than reference addresses, using a wrapper class’s equals is the right approach.
This post is licensed under CC BY-NC 4.0 by the author.