Reputation: 631
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?
Upvotes: 51
Views: 87518
Reputation: 432
this is literal code from java source: as you can see, @Agent_L is right
Upvotes: 4
Reputation: 2846
The answer to your question "Does this one [Objects.equals] still compare on references, or it compares on contents?" - Objects.equals does some comparisons on the references but it expects the first argument's class to implement equals() in which the comparison of contents is done as well as on reference.
Your second question about the implementation of equals in your tupple-like class having prev and next as its tupple attributes the answer is: your suggested implementation would work only if prev and next are primitives or if their type implements equals properly. So if prev for example is of type Foo, then you can use Objects.equals to test the two Foo's only if class Foo implements equals as expected.
Upvotes: 0
Reputation: 424983
The difference is the Objects.equals()
considers two nulls to be "equal". The pseudo code is:
null
or the same object, return true
null
return false
equals()
method of the first parameter This means it is "null safe" (non null safe implementation of the first parameter’s equals()
method notwithstanding).
Upvotes: 101
Reputation: 2172
Objects.equals just calls it's first arguments .equals method. In java, if you want to be able to test for equality in instances of a class you made, then you have to override the equals method. instance.equals() only uses == if that instances type doesn't override the equals method.
Upvotes: -4