Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing references in Java

Tags:

java

Let's say that you have overridden an object's equals() and hashCode() methods, so that they use the object's fields.

How you do you check if two references are to the same object, ala the stock equals() method?

like image 602
tunaranch Avatar asked Oct 20 '08 01:10

tunaranch


People also ask

What is reference comparison?

When a reference type is compared to a primitive type, the reference types actual value is compared to the value of the primitive type. However when two reference types are compared, the references themselves are compared, not the values.

Should I use == or .equals Java?

== should be used during reference comparison. == checks if both references points to same location or not. equals() method should be used for content comparison. equals() method evaluates the content to check the equality.

What is difference between == equals () and compareTo () method?

The equals() tells the equality of two strings whereas the compareTo() method tell how strings are compared lexicographically.

How do you compare two points in Java?

pointOne. equals(pointTwo); Determines whether or not two points are equal. Two instances of Point2D are equal if the values of their x and y member fields, representing their position in the coordinate space, are the same.


1 Answers

Use == on objects to perform identity comparison.

That is what the default implementation of equals() does, but one normally overrides equals() to serve as an "equivalent content" check.

like image 86
joel.neely Avatar answered Sep 19 '22 21:09

joel.neely