Duplicate :
|
|
Relates :
|
|
Relates :
|
|
Relates :
|
|
Relates :
|
|
Relates :
|
|
Relates :
|
The Object methods equals and hashValue define an equivalence relation among objects. Similarly, the Comparable method compareTo defines an ordering. The Comparator interface defines a way to impose an external ordering among objects. Why isn't there similarly a way to impose an external equivalence relation among objects? I have some nontrivial applications in which I'd like to look at a set of objects from different points of view (that is, under different equivalence relations at different points in my code), but the absence of an externally imposable equivalence relation forces me to wrap all the objects in order to view them under a different equivlence relation. If I'm lucky then the two default equivalence relations (identity and natural) may be just what I need, but I suspect not. If there were an externally imposable equivalence relation, it would be an interface with two methods: interface Equivalence { int hashValue(Object); boolean equals(Object, Object); } Two standard (and trivial) instances would be provided: the identity equivalence relation and the natural equivalence relation. I believe separating things this way makes it much easier to have a number of interesting variants on maps and sets without providing wholly new implementations. If the constructors are static factories, we would still have the flexibility to fully specialize the implementation for performance when one of the two standard equivalence relations is given to the static constructor. This kind of functionality can be added without making any of the existing classes obsolete.
|