簡體   English   中英

我如何獲得此HashMap <Integer[], Integer> 以我想要的方式工作?

[英]How do I get this HashMap<Integer[], Integer> to work the way I want it to?

在我的程序中,我想使用Integer []的HashMap,但是檢索數據時遇到了麻煩。 經過進一步調查,我發現此程序在程序中沒有任何其他內容的情況下輸出null

HashMap<Integer[], Integer> a = new HashMap<Integer[], Integer>();
Integer[] b = {5, 7};
Integer[] c = {5, 7};
a.put(b, 2);
System.out.println(why.get(c));

如果不需要,我不想使用a.keySet()遍歷HashMap。 還有其他方法可以達到期望的結果嗎?

數組是根據從對象本身計算的哈希而不是基於其中包含的值存儲在映射中的(在數組中使用==和equals方法時,會發生相同的行為)。

您的密鑰應該是正確實現.equals和.hashCode的集合,而不是普通數組。

檢查以下代碼以了解不良行為:

// this is apparently not desired behaviour
{
    System.out.println("NOT DESIRED BEHAVIOUR");
    HashMap<Integer[], Integer> a = new HashMap<Integer[], Integer>();
    Integer[] b = { 5, 7 };
    Integer[] c = { 5, 7 };
    a.put(b, 2);
    System.out.println(a.get(c));
    System.out.println();
}
// this is the desired behaviour
{
    System.out.println("DESIRED BEHAVIOUR");
    HashMap<List<Integer>, Integer> a = new HashMap<List<Integer>, Integer>();
    int arr1[] = { 5, 7 };
    List<Integer> b = new ArrayList<Integer>();
    for (int x : arr1)
        b.add(x);

    int arr2[] = { 5, 7 };
    List<Integer> c = new ArrayList<Integer>();
    for (int x : arr2)
        c.add(x);

    System.out.println("b: " + b);
    System.out.println("c: " + c);
    a.put(b, 2);
    System.out.println(a.get(c));
    System.out.println();
}

輸出:

NOT DESIRED BEHAVIOUR
null

DESIRED BEHAVIOUR
b: [5, 7]
c: [5, 7]
2

您可能還需要檢查以下兩個問題:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM