简体   繁体   English

HashMap.containsKey()返回false。 为什么?

[英]HashMap.containsKey() returns false. Why?

Here's my code: 这是我的代码:

class Main{
    static HashMap<Wrapper, Thing> map = new HashMap<Wrapper, Thing>();

    public static void main(String[] args){
        map.put(new Wrapper(1,2,3), new Thing(...));
        System.out.println(map.containsKey(new Wrapper(1, 2, 3)); // prints 'false'
    }

    private static class Wrapper{
        int[] array;
        public Wrapper(int... array){
            this.array = array;
        }
        public boolean equals(Object object){
            if(!(o instanceof Wrapper)) return false;
            return Arrays.equals(this.intervals, ((Wrapper) o).intervals);
        }
    }
}

Why does map.containsKey(new Wrapper(1, 2, 3) return false ? 为什么map.containsKey(new Wrapper(1, 2, 3)返回false

The hashCodes have to match and unless you override hashCode() it is randomly generated by default. hashCode必须匹配,并且除非您覆盖hashCode(),否则它是默认随机生成的。

Try 尝试

public int hashCode() { return Arrays.hashCode(array); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM