简体   繁体   中英

In which circumstances Java reference equality could be different to equals() equality for an object of a type which has not overridden equals()?

Is there any magic hanging around anywhere that could mean that

(object0 == object1) != (object0.equals(object1))

where object0 and object1 are both of a certain type which hasn't overridden Object.equals()?

No. That's exactly the definition of Object. equals() .

...this method returns true if and only if x and y refer to the same object (x == y has the value true) ...

public boolean equals( Object o ) { 
   return this == o;
}

Yes, if by "The type of object0 doesn't override Object.equals() " you mean the specific type and not a superclass.

If object0 and object1 are of type B, B extends A, and A overrides equals(Object obj) but B doesn't, then it is possible that B doesn't override equals(Object obj) but (object0 == object1) != (object0.equals(object1)) .

Well, if object0 == null and object1 == null , the first will deliver true , and the second a NullPointerException . Apart from that, there should be no observable difference.

Although the objects don't override equals() themselves, it is possible that one of superclasses of the object overrides the equals() method.

If you are using eclipse: open the object.java file and press control-o twice. Type ' equals ' and check if you only see one ' equals ' method: the equals method of Object.

The Object.java src defines its equals method as;

 return (this == obj)

so no :-)

是的, null == null为真,但null.equals(null)

不,如果equals()没有被覆盖,如果对象是内存中的相同对象,则返回 true。

No. The actual class of object0 (not necessarily the declared type of the variable) must have overridden equals() . Try printing out:

object0.getClass()

Here is the source code for Object.equals:

public boolean equals(Object obj) {
  151           return (this == obj);
  152       }
  153   

So, No.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM