An int[]
won't work because (see equals vs Arrays.equals in Java):
public static void main(String[] args) throws Exception {
int[] one = new int[] { 1, 2, 3 };
int[] two = new int[] { 1, 2, 3 };
System.out.println(one.equals(two)); // <<--- yields false
}
But, if:
Map<List<Integer>, Object> store = new HashMap<>();
Then you can:
store.put(Arrays.asList(12, 43), myObject);
myObject == store.get(Arrays.asList(12, 43));
Or maybe a little more OO - create type StoreKey
that simply encapsulates the List
:
public final class StoreKey {
private List<Integer> keyParts;
public static StoreKey of(int... is) {
return new StoreKey(IntStream.of(is)
.boxed()
.collect(Collectors.toList()));
}
public StoreKey(List<Integer> keyParts) {
this.keyParts = keyParts;
}
@Override
public int hashCode() {
return keyParts.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof StoreKey)) {
return false;
}
return this.keyParts.equals(((StoreKey) obj).keyParts);
}
}
And then:
Map<StoreKey, Object> store = new HashMap<>();
store.put(StoreKey.of(12, 43), myObject);
Finally, we can see this will work as a key because:
public static void main(String[] args) throws Exception {
StoreKey one = StoreKey.of(1, 2, 3);
StoreKey two = StoreKey.of(1, 2, 3);
System.out.println(one.equals(two)); // <<--- yields true
}