Java Generics: Useing multiple generic types in one collection type

I would like to use two generic types as a key for a hash map. Effectively:

    Map<CollectionType<Integer, Integer>, Character> map = new HashMap<>();

I am trying to find if this is possible, and if so which collection type I could use. The right type needs to be able to accept duplicate values. i.e. <1, 0>, <1, 1>, <2, 0> could all be used as a key in the map

for additional background the key in the map will be coordinates on a hex grid, and the value is what is currently stored at that location.

1 answer

  • answered 2018-11-20 03:46 Kartik

    Use a Pair<Integer, Integer>, provided by many libraries like in org.apache.commons.lang3.tuple.Pair or in jdk as javafx.util.Pair.

    equals() and hashcode() are overridden, so it can work as a key in the Map.

    Map<Pair<Integer, Integer>, Character> map = new HashMap<>();