简体   繁体   中英

Implementing hashCode() and equals() in class with no fields

I have an abstract class which will be used in a Hashtable:

public abstract class CEvent {

    abstract public void finished();
}

How to implement hashCode() if it does not have any field, only methods? Should i rely on Object implementation of hashCode?

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() . If two objects are considered equal they should return the same hash code. See the Java documentation on object for more details.

hashCode

You can implement hashCode in the abstract class if it can obtain the information required for hashing from abstract methods. The Java class AbstractList does this. 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.

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. this will have no effect on your code as you dont have anything to compare.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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