A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李计伟 中级黑马   /  2012-11-6 22:54  /  1491 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文


  1. <P> public class Student {
  2.           private String name;
  3.           private int age;
  4.           //省略无参构造器get()/set()方法toString()方法
  5.           public Student(String name,int age){
  6.           this.name = name;
  7.           this.age = age;
  8.            }
  9.           public void setAge(int age) {
  10.                 this.age=age;
  11.           }

  12.           //重写equals方法
  13.            public boolean equals(Object obj) {
  14.                  if(this ==obj){
  15.                  return true;
  16.                  }
  17.                 if(!(obj instanceof Student)){
  18.                 return false;
  19.                  }
  20.                 Student s = (Student)obj;
  21.                 return this.name.equals(s.name)&&this.age==s.age;
  22.             }
  23.             //重写hashCode()方法
  24.            public int hashCode() {
  25.                 return this.name.hashCode()+this.age*13;
  26.            }
  27. }</P>
复制代码
  1. import java.util.HashSet;

  2. public class MainApp {
  3.          public static void main(String[] args) {
  4.          HashSet<Student> list = new HashSet<Student>();
  5.                 Student s1 = new Student("小黑", 20);
  6.                 Student s2 = new Student("小白", 30);
  7.                 Student s3 = new Student("小黑", 20);
  8.                     //加入三个对象
  9.                 list.add(s1);
  10.                 list.add(s2);
  11.                 list.add(s3);
  12.                 //更改hashCode()值
  13.                 s1.setAge(24);
  14.                 //删除s1
  15.                 list.remove(s1);
  16.                 System.out.println(list.size());
  17.          }
  18. }
复制代码
HashSet底层数据结构是哈希表。
s1和s3的哈希值一样所以删除s1也就删除了s3,当把哈希值改变后,s1没有被取走结果是 2,不执行这句list.remove(s1);的结果是 1。
提示:当一个对象被存储进HashSet集合后就不能修改这个对象中的那些参与计算哈希值的字段了。
否则有内存泄露的隐患。因为删除对象时没有释放资源,如果以后要多次对对象存删,时间长了就会造成内存泄露。


评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 赞一个!

查看全部评分

3 个回复

倒序浏览
沙发哦!  呵呵  
回复 使用道具 举报
楼主你确定你的list.remove(s1)是运行了吗?
System.out.println(list.remove(s1)); 我怎么输出是false呢。。。
回复 使用道具 举报
王永荣 发表于 2012-11-7 09:32
楼主你确定你的list.remove(s1)是运行了吗?
System.out.println(list.remove(s1)); 我怎么输出是false呢。 ...

输出false是因为,s1对象的哈希值改变了,因此无法从集合中找到与此哈希值对应的集合对象

评分

参与人数 1技术分 +1 收起 理由
冯海霞 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马