0

I need to store custom Objects as a value in a Dictionary like datastrukturer with two composite integer Keys. (composite IDs)

I tried using arrays as keys but both don't work, because i guess that's just the pointer to that arrays, where used as the keys

It would be perfect if i could use is like

store.put([12,43],myObject);
store.get([12,43]);
electron2302
  • 37
  • 1
  • 4
  • If these numbers in the array have some meaning, you might consider create a java class and use it as the key. Then you get to control how these objects are compared and it's easier for the users as well. – Hua Mar 26 '19 at 21:41

1 Answers1

1

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
}
Not a JD
  • 1,864
  • 6
  • 14