复合int具有值的键

问题描述 投票:0回答:1

我需要将自定义对象存储为字典中的值,如datastrukturer,其中包含两个复合整数键。 (复合ID)

我尝试使用数组作为键,但两者都不起作用,因为我猜这只是指向该数组的指针,用作键

如果我可以使用就像是完美的

store.put([12,43],myObject);
store.get([12,43]);
java key-value composite-key
1个回答
1
投票

int[]不起作用,因为(见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
}

但是,如果:

Map<List<Integer>, Object> store = new HashMap<>();

然后你可以:

store.put(Arrays.asList(12, 43), myObject);
myObject == store.get(Arrays.asList(12, 43));

或者可能多一点OO - 创建类型StoreKey,只是封装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);
    }

}

然后:

Map<StoreKey, Object> store = new HashMap<>();
store.put(StoreKey.of(12, 43), myObject);

最后,我们可以看到这将作为关键因素:

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
}
© www.soinside.com 2019 - 2024. All rights reserved.