Reputation: 387
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?
Upvotes: 9
Views: 3824
Reputation: 863
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();
}
Upvotes: 9
Reputation: 8841
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.
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.
Upvotes: 8
Reputation: 1186
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.
Upvotes: 1