243 HashSet集合存储学生对象并遍历
这个案例练习过多次了,用HashSet来做有什么不同?——如果学生对象的成员变量值相同,视为同一个对象
不做特殊处理前,相同姓名、年龄的学生时可以重复添加到HashSet里的
如何保证相同的元素不重复添加?——重写equals()方法和hashCode()方法即可,且使用generator工具可便捷地实现重写
(在Student类里)右键-generator-construct- equals and hashCode
--------------------------------------------------------------
package e243;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getclass() != o.getclass()) return false;
//
// Student student = (Student) o;
//
// if (age != student.age) return false;
// return name != null ? name.equals(student.name) : student.name == null;
// }
//
// @Override
// public int hashCode() {
// int result = name != null ? name.hashCode() : 0;
// result = 31 * result + age;
// return result;
// }
}
--------------------------------------------------------------
package e243;
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
HashSet
Student s1 = new Student("TWO",22);
Student s2 = new Student("HUNDRED",22);
Student s3 = new Student("FORTY",22);
Student s4 = new Student("FORTY",22);
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
System.out.println("19.");
for (Student s:hs){
System.out.println(s.getName()+","+s.getAge());
}
}
}
--------------------------------------------------------------
19.
TWO,22
FORTY,22
HUNDRED,22
FORTY,22
--------------------------------------------------------------
package e243;
public class Student {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getclass() != o.getclass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
}
--------------------------------------------------------------
19.
FORTY,22
HUNDRED,22
TWO,22
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)