Enzio
Enzio

Reputation: 889

Why does the equals() method return false when the two objects are identical?

public class Test {
    public static void main(String[] args) {
        Object o1 = new Object();
        Object o2 = new Object();
        System.out.print((o1 == o2) + " " + (o1.equals(o2)));
    }
}

I read this in a different answer:

The == operator tests whether two variables have the same references (aka pointer to a memory address).

Whereas the equals() method tests whether two variables refer to objects that have the same state (values).

Here, since o1 and o2 reference two different objects, I get why == returns false.

But both the objects are created using the default constructor of the Object class, and therefore have same values. Why does the equals() method return false?

Upvotes: 0

Views: 4363

Answers (3)

kkica
kkica

Reputation: 4104

You have to write your own equals method that overrides the equals method of class Object because that method returns true if this object is the same as the object in the argument and false otherwise.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). (for more information, read Javadoc)

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234645

The implementation of equals() supplied by java.lang.Object is defined to return false, unless the references refer to the same object, in which case it returns true.

This is by design (the method mimics the behaviour of ==) and encourages programmers to implement their own version of equals(), if appropriate, for their class. For example, see java.lang.String#equals which compares the contents if another String is passed as an argument.

Upvotes: 6

scottb
scottb

Reputation: 10084

All Java objects inherit from the Object class. The methods of Object, therefore, are available to all Java objects. One of these methods is equals().

The implementation for equals() in class Object, by default, is identical to the == operator.

If a programmer wishes to use equals() to test objects for value equality, he must override equals() and provide his own implementation (that should comply with the general contract for equals(); refer to the Javadoc).

Upvotes: 2

Related Questions