首页 > 其他 > 详细

关于HashSet的equals和hashcode的重写

时间:2019-01-29 13:22:42      阅读:208      评论:0      收藏:0      [点我收藏+]

关于HashSet的equals和hashcode的重写:
package
Test; import java.util.HashSet; import java.util.Set; public class HashSetTest { public static void main(String[] args) { Set hs = new HashSet(); hs.add(new Student("张三")); hs.add(new Student("lisi")); hs.add(new Student("张三")); hs.add(new Student("lisi")); hs.stream().forEach(x -> System.out.println(x)); } } class Student { String name; public Student(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return name; } @Override public int hashCode() { return getName().hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof Student && this.name.equals(((Student) obj).getName())) { return true; } return false; } }

//说明:equals(桶中定位)和hashcode(散列分桶)要一起重写

 

关于HashSet的equals和hashcode的重写

原文:https://www.cnblogs.com/shijinglu2018/p/10333542.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!