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

时间:2014-09-14 00:04:13

标签: java hashmap

这是我的代码:

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);
        }
    }
}

为什么map.containsKey(new Wrapper(1, 2, 3)会返回false

1 个答案:

答案 0 :(得分:2)

hashCodes必须匹配,除非你覆盖hashCode(),否则它是默认随机生成的。

尝试

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