标签: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(散列分桶)要一起重写
标签:new hashcode his oid add this imp ring als
原文地址:https://www.cnblogs.com/shijinglu2018/p/10333542.html