【问题标题】:Overriding equals() method in a generic class覆盖泛型类中的 equals() 方法
【发布时间】:2013-08-20 21:03:27
【问题描述】:

我想在这个类中重写 equals() 方法。我在覆盖 equals() 方法时遵循通常的规则,但是我将 Object 类型转换为我的类类型

但在我的 equals() 方法中,我只想在对象属于相同的泛型类型时才返回 true。

如何在我的 equals() 方法中检查实例的运行时类型?

这是我的代码:

public class GenericsRunTimeType<T> {

private T foo;
public GenericsRunTimeType(T foo){
    this.foo = foo;

}

@Override
public boolean equals(Object obj){
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;

    // Before doing this I want to test if obj and this are of the same generic type
    GenericsRunTimeType other = (GenericsRunTimeType) obj;
    if(other.equals(obj))
        return true;
    else
        return false;
}

}

【问题讨论】:

  • 它没有给出想要的结果吗? if (getClass() != obj.getClass())

标签: java generics


【解决方案1】:

在您的情况下,您可以检查:

foo.getClass().equals(other.foo.getClass())

这是因为您的班级中已经有 T 班级的成员。但是,在通常情况下,当您没有此类成员时,请查看@Rohit Jain 所做的回答。 (+1)

【讨论】:

  • 但是,仅仅因为foo.getClass().equals(other.foo.getClass())并不意味着类型参数相同。相反,类型参数可能相同,foo.getClass().equals(other.foo.getClass()) 可能不正确。
【解决方案2】:

一种选择是使用Reflection,但我认为这是我最后的手段。

我更喜欢的另一个选项是在构造函数中传递Class&lt;T&gt; 参数,并将其存储在一个字段中:

private T foo;
private Class<T> clazz;
public GenericsRunTimeType(T foo, Class<T> clazz){
    this.foo = foo;
    this.clazz = clazz;
}

然后在equals 方法中,像这样进行比较:

if (this.clazz == ((GenericsRunTimeType)obj).clazz) {
    System.out.println("Same type");
}

【讨论】:

    【解决方案3】:

    我给另一个方向:你真的需要检查 TYPE PARAMETER 的相等性吗?

    鉴于您的示例中的foo 应该是等式的一部分,通常equals() 方法应该看起来像

    public boolean equals(Object obj){
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!obj instanceof GenericsRunTimeType)
            return false;
    
        GenericsRunTimeType other = (GenericsRunTimeType) obj;
    
        return (this.foo.equals(obj.foo))  // !Here
        // can be better wrote as foo==obj.foo || (foo != null && foo.equals(obj.foo))
        // I wrote in a simpler form just to give you the idea
    
    }
    

    这两个foo是否属于同一类型,一般由foo的equals()负责处理。如果你不关心这两个foo是否相等,那你为什么要关心这两个foos是否属于同一类型呢?

    当然还有其他选择,例如其他答案所建议的,您可以从foo 获取类型并比较它们或传入另一个Class 对象。但是我认为在大多数情况下可能没有必要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-14
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      • 2014-05-27
      • 2013-04-04
      相关资源
      最近更新 更多