2

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.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
jwmorse
  • 23
  • 3

1 Answers1

3

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<>();
Kartik
  • 7,677
  • 4
  • 28
  • 50