简体   繁体   English

如何在非属性泛型类中覆盖 equals 方法?

[英]How to override equals method in a non-attributes generic class?

I have a generic class that has no attributes, but a method with generic type.我有一个没有属性的泛型类,但有一个具有泛型类型的方法。 How can I override the equals method for it?如何覆盖它的 equals 方法?

   public Foo<T> {
       boolean method(T bar){
           if (bar instanceOf Boolean) // do something and return 
           if (bar instanceOf String) // do something and return
           return false;
       }
   }

And intuitional Foo<String> s and Foo<Boolean> b should be different, so how can I override the equals to reflect this?直观的Foo<String> sFoo<Boolean> b应该是不同的,那么我该如何覆盖 equals 来反映这一点呢? Or it is bad to write a class like this?还是写这样的类不好?

It seems to me that if there are no attributes (which I take to mean instance fields), then the class should probably not be capable of being instantiated and the methods should be declared static (like the Math class in the Java API).在我看来,如果没有属性(我认为是指instance字段),那么该类可能无法被实例化,并且该方法应该声明为static (如 Java API 中的Math class )。 In any event I don't believe you would need to override equals since it doesn't seem likely you would compare multiple instances.无论如何,我认为您不需要覆盖 equals,因为您似乎不太可能比较多个实例。 You could do your example method as follows:您可以按如下方式执行示例方法:

    public static <T> boolean method(T foo) {
        if (foo instanceof String) {
            System.out.println("You passed a string");
            return true;
        } 
        if (foo instanceof Integer) {
            System.out.println("You passed an integer");
            return true;
        }
        return false;
    }

But if you really want to override equals, you could do something like this.但是如果你真的想覆盖 equals,你可以做这样的事情。

@Override
public boolean equals(Object o) {
   return this == o;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM