class KeyMaster {
    public int i;
    public KeyMaster(int i) {this.i = i;}
    public boolean equals(Object o) {return i == ((KeyMaster) o).i;}
    public int hashCode() {return i;}
}public class MapIt {
    public static void main(String[] args) {
        Set<KeyMaster> set = new HashSet<KeyMaster>();
        KeyMaster k1 = new KeyMaster(1);
        KeyMaster k2 = new KeyMaster(2);
        set.add(k1);
        set.add(k1);
        set.add(k2);
        set.add(k2);
        System.out.print(set.size() + ":");
        k2.i = 1;
        System.out.print(set.size() + ":");
        set.remove(k1);
        System.out.print(set.size()+":");
        set.remove(k2);
        System.out.print(set.size());
    }
}为什么输出的结果是2:2:1:1而不是2:2:1:0呢?

解决方案 »

  1.   

    呵呵,这道题考的是SET的内部实现,无论Add还是Remove,SET都要判断操作的对象在不在SET中,而依据就是对象的hashCode值,最后一次删除,因为K2的HashCode在运行时已经发生了改变,与加入SET时值不一样,所以set.remove(k2) 返回null, 实际上没有删除成功。
      

  2.   


    哈哈,我也在想应该是hashcode的问题,但是没法像这位大侠一样解释出来,顶~