Map interface and equals()

The Map interface cannot have duplicate keys and implies that equals is used to determine this.

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.

Comments

  1. Trove4J 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.

    ReplyDelete
  2. I 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.

    While `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?

    ReplyDelete

Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Comparing Approaches to Durability in Low Latency Messaging Queues