简体   繁体   English

在没有字段的类中实现hashCode()和equals()

[英]Implementing hashCode() and equals() in class with no fields

I have an abstract class which will be used in a Hashtable: 我有一个抽象类,将在Hashtable中使用:

public abstract class CEvent {

    abstract public void finished();
}

How to implement hashCode() if it does not have any field, only methods? 如果没有任何字段,只有方法,如何实现hashCode()? Should i rely on Object implementation of hashCode? 我应该依赖hashCode的Object实现吗?

If the class is abstract, then it must have concrete subclasses. 如果类是抽象的,那么它必须具有具体的子类。 You implement the hash code method in the concrete subclasses. 您可以在具体子类中实现哈希码方法。

You should ensure that hashCode() is consistent with equals() . 您应该确保hashCode()equals()一致。 If two objects are considered equal they should return the same hash code. 如果认为两个对象相等,则应返回相同的哈希码。 See the Java documentation on object for more details. 有关更多详细信息,请参阅对象的Java文档。

hashCode 的hashCode

You can implement hashCode in the abstract class if it can obtain the information required for hashing from abstract methods. 如果可以从抽象方法获取散列所需的信息,则可以在抽象类中实现hashCode The Java class AbstractList does this. Java类AbstractList执行此操作。 However, you will need to be happy that by default, different derived classes will inherit that method and will return the same hash code for similar data. 但是,您需要感到高兴的是,默认情况下,不同的派生类将继承该方法,并将为类似数据返回相同的哈希代码。 In your case, it does not make sense to implement the hashCode function in the abstract class. 在您的情况下,在抽象类中实现hashCode函数没有意义。

Actually, you can use the following as the default behaviour: 实际上,您可以使用以下作为默认行为:

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

@Override
public int hashCode() {
    return CEvent.class.hashCode();
}

Just use super class(Object) equals and hascode implementation in this case. 在这种情况下,只需使用超类(Object)equals和hascode实现。 this will have no effect on your code as you dont have anything to compare. 这对你的代码没有任何影响,因为你没有什么可比的。

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

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