Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The behaviour of equals() method in Java [duplicate]

Tags:

java

Consider the following Java code:

    Object a = new Integer(2);
    Object b = new Integer(2);
    System.out.println(a.equals(b));

    Object x = new Object();
    Object y = new Object();
    System.out.println(x.equals(y));

The first print statement prints true and the second false.

If this is an intentional behavior, how this helps programming in Java?

If this is not an intentional behavior, is this a defect in Java?

like image 323
siva636 Avatar asked Feb 14 '12 13:02

siva636


2 Answers

I'm going to answer your question with reservations, but you should know that you are hurting yourself if the intent of the question was to get you to learn and your solution was to ask StackOverflow. That aside...

This behavior is intentional.

The default equals() method on java.lang.Object compares memory addresses, which means that all objects are different from each other (only two references to the same object will return true).

java.lang.Integer overrides this to compare the value of the Integers, so two different Integers both representing the number two compare equal. If you used == instead, you would get false for both cases.

Standard practice in Java is to override the equals method to return true for objects which have the same logical value, even if they were created at different times (or even with different parameters). It's not very useful to have objects representing numbers if you don't have a way to ask, "do these two things represent the same value?".

Incidentally, and this is a tangent here, Java actually keeps a cache of Integer objects for small values. So sometimes you may get two Integer objects where even the == operator will return true, despite you getting them from two different sources. You can even get code that behaves differently for larger integers than it does for smaller, without having it look at the integral values!

like image 74
Borealid Avatar answered Oct 10 '22 01:10

Borealid


This is intended behaviour.

Object.equals() considers the object identity (i.e. an object is only equal to itself), which is the only thing you can do for generic objects.

Integer overrides the method to depend on the integer value, since two Integer objects with the same value are logically equal. Many other classes also override equals() since it's a core mechanism of the standard API and a lot of functionaliy e.g. in the collections framework depends on it.

Why do are you puzzled by the behaviour anyway? Most people are only confused by the == operator not behaving like that (it works like Object.equals()).

like image 30
Michael Borgwardt Avatar answered Oct 10 '22 01:10

Michael Borgwardt