I wanted to use a LinkedHashSet
as a key in the Map
, but since the hashCode()
of the LinkedHashSet
object doesn't take the order of elements into consideration, my sets are considered as the same key in the map.
Map<LinkedHashSet<String>, Integer> ballotsAsSets = new HashMap<>();
for (Map.Entry<List<String>, Integer> e : ballots.entrySet()) {
LinkedHashSet<String> newKey = new LinkedHashSet<>(e.getKey());
System.out.println("key = " + newKey + ", hash = " + newKey.hashCode());
ballotsAsSets.put(newKey, e.getValue());
}
ballots = {[A, B, C]=1, [B, A, C]=3, [A, C, B]=1}
key = [A, B, C], hash = 198
key = [B, A, C], hash = 198
key = [A, C, B], hash = 198
It seems counterintuitive.