HashSet显示更多值 [英] HashSet showing more values

查看:110
本文介绍了HashSet显示更多值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 MIt 
{
 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.println(set.size()+":");

  k2.i = 1; // this is creating another object in HashSet
  set.remove(k1);
  System.out.println(set.size()+":");
  set.remove(k2);
  System.out.print(set.size());
}
}

我在HashSet中添加了两个对象,并将其删除,但是在最后一个sop中,我的大小仍然为1.我同意我已经更新了k2的值,但仍然没有将其添加到我的集合中.

I have added two object to the HashSet and have removed it, but in the last s.o.p I still have size 1. I agree I have updated the value of k2 but still I haven't added that to my set.

推荐答案

哈希集使用哈希存储和检索对象.当我们在哈希图中添加对象时,JVM会查找哈希码,以确定将对象放置在内存中的位置.当我们再次检索对象时,将使用哈希码来获取对象的位置.如果在将对象插入哈希表之后更改对象,则更新后的对象将具有与原始存储的对象不同的哈希码.就像您更新k2.i = 1的情况一样,k2的哈希码现在将不同于原始k2对象.因此,当您使用更新的k2调用remove时,JVM实际上找不到该对象,因此无法删除.这就是为什么您在最后一个s.o.p

Hashset uses hashing to store and retrieve the objects. When we add an object in hashmap, JVM looks for the hashcode implentation to decide where to put the object in memory. When we retrieve an object again hashcode is used to get the location of the object. If you change an object after inserting it into a hashmap, the updated object will have a different hashcode than the originally stored object. As in your case when you update k2.i=1, hashcode for k2 will now be different from original k2 object. So when you call remove with updated k2, JVM actually couldn't find the object and hence not able to delete. Thats the reason why you see the size as 1 in your last s.o.p

这篇关于HashSet显示更多值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆