Overriding “equals” method: how to figure out the type of the parameter?

前端 未结 9 1274
栀梦
栀梦 2021-02-05 07:47

I\'m trying to override equals method for a parameterized class.

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return t         


        
9条回答
  •  攒了一身酷
    2021-02-05 08:26

    The suggestions to retain a reference to E's type with a Class object seem inefficient (that's a lot of pointless references to a Class taking up memory) and pointless for your problem.

    It's not generally true that Foo andFoo should be unequal. So you don't need E. And, in the code you wrote, you don't even need it to compile. Simply cast to Tuple, since that is truly all you know about Tuple at that point. It still compiles and all.

    If you are passed Tuples with data of two wildly different types, those elements will not be equals, and your method will return false, as desired. (One hopes -- depends on those types implementing equals sanely.)

提交回复
热议问题