1

It seems to me that any scenario where I instantiate a HashMap using an interface for a key-type would work contrary to the idea of the map. Take the following example:

HashMap<MyInterface, Integer> map = new HashMap<MyInterface, Integer>();

If I put 2 objects of different MyInterface implementations into the map then they will both operate on their own hashCode() implementations and the entire underlying logic of the HashMap no longer makes sense. So my question is, is there ever a proper time for using interfaces as keys in HashMaps?

soren.qvist
  • 7,080
  • 14
  • 55
  • 87
  • 4
    I think you're slightly misunderstanding how a `HashMap` works. As long as `hashCode()` for the keys you put in obey the general contract of `hashCode()`, there shouldn't be a problem with different implementations. If that were the case, you wouldn't be able to use an `Object` key, and in fact raw type `HashMap`s wouldn't work at all. For your second question, you'd use an interface for the key if you want your keys to be of a particular type, but don't care about the specific implementation of that type. `hashCode()` has nothing to do with it. – awksp Jun 10 '14 at 21:57
  • It might help you [How hash map works in java](http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html) – Braj Jun 10 '14 at 22:02
  • 2
    My main concern with use of an interface is that keys should be immutable objects, and with an interface, you would have less control guaranteeing that the keys are in fact immutable. – Hovercraft Full Of Eels Jun 10 '14 at 22:04
  • The instance fields that are used in `hashCode()` must not be changeable. It means it should be immutable to make a consistent hash code every time. `ENUM` as key will be good. It might help you [Overriding equals and hashCode in Java](http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java) – Braj Jun 10 '14 at 22:06

2 Answers2

0

they will both operate on their own hashCode() implementations and the entire underlying logic of the HashMap no longer makes sense

I guess by that you meant hash collision. Hash collision does not corrupt the hash map. In java, you need to properly implement "equals" together with "hashCode" for the hash map to resolve the key.

James
  • 478
  • 2
  • 9
0

How about:

Map<Connection,AtomicInteger> outstandingQueries = new HashMap<>();

A java.sql.Connection is an interface and this Map makes sense. Implementation of equals and hashCode can still distinguish objects of different types.

OldCurmudgeon
  • 60,862
  • 15
  • 108
  • 197