Re: equals(), Sets, Maps, and degrees of equality
On 11/10/11 6:31 AM, Sean Mitchell wrote:
On Nov 9, 10:11 pm, Eric Sosman<esos...@ieee-dot-org.invalid> wrote:
Seems odd: Why should Fido rather than Rover or Wossname be the
sole representative Cocker Spaniel?
Just cuz.
Silly example: Father-in-law is going hunting. He has a kennel full of
dogs. Wants a hound and a bird dog. Doesn't care which exact ones.
Two avenues of attack seem plausible. One, as you mention, is to
use a helper class to designate the chosen "identity" attributes. I
think I'd prefer to make it an inner class rather than a wrapper class,
but maybe that just means I'm still too hung up on your dogs and breeds.
Hmmm. This is interesting. How would it work? So, I'd have an inner
class for each type of equality I need, basically exposing its parent
and providing the desired equals()? Think I'll play around with that
idea.
The other approach is to implement your own BreedSet that uses
breedEquals() and breedHashCode() instead of the usual methods (and,
of course, documents that fact in large red letters). But this feels
an awful lot like the first step down a slippery slope, one that may
find you implementing umpty-leven specialized variations of Set and
Map and regretting the original choice ...
Yes, as I said in my reply to Owen (which I think I accidentally sent
as reply to author), if possible I'd rather use smarter people's work
than write my own implementation. His TreeSet/TrreMap proposal is my
favourite solution so far.
Cheers,
Sean
I've often wanted the equivalent of "Comparator" for the Hash
implementations of Map/Set.
public interface HashStrategy<T> {
int hash(T object);
boolean equivalent(T a, T b);
}
public class DefaultHashStrategy<T> extends HashStrategy<T> {
public int hash(T object) {
return object == null ? 0 : object.hashCode();
}
public boolean equivalent(T a, T b) {
return a == null ? b == null : a.equals(b);
}
}
public class HashMap<K,V> implements Map<K,V> {
private final HashStrategy<? super K> hashStrategy;
public HashMap(HashStrategy<? super K> hashStrategy) {
this.hashStrategy = hashStrategy;
}
public HashMap() {
this(new DefaultHashStrategy<K>());
}
// ... the rest of the HashMap implementation.
}