Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects.equals and Object.equals

Tags:

java

equals

I try to create a tuple class that allows a tuple-like structure in Java. The general type for two elements in tuple are X and Y respectively. I try to override a correct equals for this class.

Thing is, I know Object.equals falls into default that it still compares based on references like "==", so I am not so sure I can use that. I looked into Objects and there is an equals() in it. Does this one still compare on references, or it compares on contents?

Quickly imagined the return statement as something like:

return Objects.equals(compared.prev, this.prev) && Objects.equals(compared.next, this.next); 

where prev and next are elements of tuple. Would this work?

like image 705
jfcjohn Avatar asked Dec 28 '15 01:12

jfcjohn


People also ask

What is Object equals () in Java?

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).

How do you equal two objects?

The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)

Can you use == to compare objects?

The == operator compares whether two object references point to the same object.

What is the difference between == Object equals ()?

The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.


Video Answer


2 Answers

The difference is the Objects.equals() considers two nulls to be "equal". The pseudo code is:

  1. if both parameters are null or the same object, return true
  2. if the first parameter is null return false
  3. return the result of passing the second parameter to the equals() method of the first parameter

This means it is "null safe" (non null safe implementation of the first parameter’s equals() method notwithstanding).

like image 177
Bohemian Avatar answered Sep 21 '22 12:09

Bohemian


this is literal code from java source: as you can see, @Agent_L is right this is literal code from java source: as you can see, @Agent_L is right

like image 33
Marek Kamiński Avatar answered Sep 22 '22 12:09

Marek Kamiński