有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java在for循环中的hashmap中放置了一些内容

嘿,我只是想说我是个java新手。 所以我的问题是输出是:a - null 我不知道为什么 我确实将HashMap从HashMap<Integer[], Integer> testHashMap = new HashMap<>();更改为HashMap<Integer, Integer> testHashMap = new HashMap<>(); 然后我工作

        HashMap<Integer[], Integer> testHashMap = new HashMap<>();
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                Integer[] someInteger = {i, j};
                testHashMap.put(someInteger, (i + j * 4));
            }
        }
        Integer[] someOtherInteger = {0,0};
        System.out.println("a - " + testHashMap.get(someOtherInteger));

输出:“a-null” 输出应为:“a-0”

如果这是一个愚蠢的问题,我很抱歉


共 (4) 个答案

  1. # 1 楼答案

    Java数组不提供equals方法的覆盖,只进行标识比较

    因此

    new Integer[]{0,0}.equals(new Integer[]{0,0});
    

    将返回false,Integer[]根本不是可用的类,无法用作映射的键,因为HashMap在内部为键使用equals和hashcode方法

    您应该考虑为拥有2个int值的密钥创建自己的自定义类,并在其中重写等值和哈希代码。

    但您可以使用列表,它应该可以工作:

    HashMap<List<Integer>, Integer> testHashMap = new HashMap<>();
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            List<Integer> someInteger = Arrays.asList(i, j);
            testHashMap.put(someInteger, (i + j * 4));
        }
    }
    List<Integer> someOtherInteger = Arrays.asList(0,0);
    System.out.println("a - " + testHashMap.get(someOtherInteger));
    

    将为您提供所需的输出

  2. # 2 楼答案

    正如@vakio所解释的,数组的hashCode没有考虑它们的内容

    如果确实需要为映射使用复合键,请将Integer[]键类型数组替换为列表List<Integer>

    Map<List<Integer>, Integer> testHashMap = new HashMap<>();
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            List<Integer> someInteger = Arrays.asList(i, j);
            testHashMap.put(someInteger, (i + j * 4));
        }
    }
    List<Integer> someOtherInteger = Arrays.asList(0, 0);
    System.out.println("a - " + testHashMap.get(someOtherInteger)); // a - 0
    
  3. # 3 楼答案

    在第一种情况下,对于整数数组,基本上存储为映射键的是{0,0}或{i,j}的对象引用

    当您创建其他整数时,Java会返回另一个对象引用—分配另一个内存地址。换句话说,每当Java创建一个新对象,并且数组被认为是一个对象而不是一个原语,它就会为它分配一个不同的地址

    这就是为什么当调用get给出第二个值,并持有someOtherInteger数组引用时,它返回null。映射中不存在反映其他整数的唯一地址的此键

  4. # 4 楼答案

    请阅读here

    他说:

    No way to do that with arrays, because they don't override equals() and hashCode(). You should define your own class wrapping the array, which would override equals() and hashCode() or use a List<Integer> as key instead.

    我想告诉你的是一样的

    List<Integer>代替Integer[]