Map interface and equals()
The Map interface cannot have duplicate keys and implies that equals is used to determine this.
The Maps which support this are
The Maps which don't use equals() are
All have different reasons as to why they violate the contract but it strikes me as not a great rule that it is as often violated as followed.
boolean containsKey(Object key)
Returns true if this map contains a mapping for the specified key. More formally, returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k)). (There can be at most one such mapping.)
The Maps which support this are
- HashMap
- LinkedHashMap
- ConcurrentHashMap
- Hashtable
- WeakHashMap
The Maps which don't use equals() are
- IndentityHashMap
- TreeMap
- ConcurrentSkipListMap
- EnumMap
All have different reasons as to why they violate the contract but it strikes me as not a great rule that it is as often violated as followed.
Related StackOverflow question: What does comparison being consistent with equals mean ? What can possibly happen if my class doesn't follow this principle?
ReplyDeleteTrove4J has better design -- it introduces interface THashingStrategy, which takes responsability of equality/hashing for keys. This allows to plug in different strategy of keys comparation. It's a pity JCF authors does not use approach like this.
ReplyDeleteI wouldn't say "as often violated as followed.", but it's a funny observation. Those comparison-based Maps may or may not be consistent with equals, it depends on the relation.
ReplyDeleteWhile `EnumMap` doesn't use `equals`, it's AFAIK always consistent with it. Why shouldn't it be? Maybe when you do strange things like creating enum instances reflectively?