一.自定义对象存放在hashSet中,保证元素不重复。重写hashCode()和equals()方法
public class Student{ private String name; private Integer age; public Student(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public int hashCode() { //return name.hashCode()+age; //为了让hash值的范围大一些,我们这里可以乘以一个常数 return name.hashCode()+age*39; } @Override public boolean equals(Object obj) { if (this == obj){ //如果是同一个引用,不用比较了 return true; } if (!(obj instanceof Person)){ //如果类型不能转换,不用比较了 throw new ClassCastException("类型错误"); } Student student = (Student) obj; return this.name.equals(student.name) && this.age == student.age; } }