#equals overriding for generic Pair

7 messages · Page 1 of 1 (latest)

undone walrus
#

My course says that having a generic MyClass<T>, if we have two objects MyClass<A> and MyClass<B> there is no relationship between them regardless if A and B are related and that the common parent is Object.

What I'm trying to do is implement my own Pair<T, U> and I'm a bit confused on how to implement equals because until now I'd do something like

...
if(!(obj instanceof MyClass)) return false;
...

As far as I understood I can't do this for generics, right? because their common parent is object and if I tried casting to a Pair <T, U> I could get an error at run time.
What's the proper way to write an equals() for a generic with 1, 2 or multiple types? Should I check getClass() != obj.getClass() instead?

leaden barnBOT
#

This post has been reserved for your question.

Hey @undone walrus! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

random lake
#

It's admittedly limited to special cases and possible only because any object can call equals() with any other object, regardless of whether they are related

undone walrus
#

thanks

leaden barnBOT
# undone walrus thanks

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.