What do you use in Java to check if two things are equal or not? And what’s exactly the meaning of being equal?
OK, you already probably know that you can use the operator ==
to compare primitives and objects. If you’ve read about the equals-hashCode contract you probably also know that you can compare objects using the method equals
.
However there are some important and little subtleties you must know about equality comparison before trying the exam. Let’s say you have the following code:
1 2 3 4 5 6 7 8 9 10 11 |
Integer i1 = 1; Integer i2 = new Integer(1); int i3 = 1; Byte b1 = 1; Long g1 = 1L; |
These are the 5 things you must remember:
i1 == i2
will returnfalse
because they are pointing to different objects.i1 == i3
will returntrue
because one operand is a primitiveint
and so the other will be unboxed and then the value will be compared.i1 == b1
will not even compile because type ofi1
andb1
references are classes that are not in the same class hierarchy, so the compiler knows that they can’t point to the same object.i1.equals(i2)
will returntrue
because both areInteger
and both have a value of1
.i1.equals(b1)
andi1.equals(g1)
will returnfalse
because they are pointing to objects of different types. The signature of the equals method isboolean equals(Object o)
so it can take any object and there will be no compilation error. However theequals
method of all wrapper classes first checks if the two objects are of same class and if they aren’t, it immediately returnsfalse
.