码迷,mamicode.com
首页 > 其他好文 > 详细

关于HashSet的equals和hashcode的重写

时间:2019-01-29 13:56:54      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:new   hashcode   his   oid   add   this   imp   ring   als   


关于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的重写

标签:new   hashcode   his   oid   add   this   imp   ring   als   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!