What do you mean by "not be managed in hash tables" ? Of course, objects whose equality state - fields compared by equals() - changes during their live time should not be used as KEYS in maps. But they may of course be perfectly used as VALUES.+1 for overriding hashCode() returning a constant integer for mutable classes. i don't fully agree with the javadoc though. if you implement hashCode() 'correctly', i.e. calculate the hashcode based on the objects fields, you risk losing track of data in a hash table.
mutable objects should imo never be managed in hash tables.
returning a constant integer is therefore fine with me for mutable
objects.
Now, it makes perfect sense to not use variable KEYS. This is not specific to java, this is also true for any database application.
well, when the equality depends on mutable data, the object cannot be used in sets at all.
True, or as the JavaDoc of the Set interface states:
Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object isan element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.
There is no need for that ! Simply document the class to be mutable regarding equality and the rest is in the responsibility of the programmer !so no need to return '1' as hashcode. if the object cannot be used in set, i would rather throw a UnsuportedOperationException:
public int hashCode() {
thrown new UnsupportedOperationException("unable to compute hashcode");
}
In fact the proposed behavi is very dangerous and may lead to unexplainable situations.
Yes, I am picky on that. But this is not an issue of style but an issue of correctness !
Regards Felix
