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?
Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.
If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.
"If two objects are equal using Object class equals method, then the hashcode method should give the same value for these two objects." So, if in our class we override equals() we should override hashcode() method also to follow this rule.
The hashCode() method should return the same integer value for the same object for each calling of this method unless the value stored in the object is modified. If two objects are equal(according to equals() method) then the hashCode() method should return the same integer value for both the objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With