Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

java - Objects.equals and Object.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?

question from:https://stackoverflow.com/questions/34486832/objects-equals-and-object-equals

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...