Student.java:
public class Student {
private String username;
private int age;
public Student(String username, int age) {
super();
this.username = username;
this.age = age;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}
test.java:
public class test {
public static void main(String[] args) {
//创建集合
HashSet<Student> hs=new HashSet<Student>();
//创建学生对象
Student s1=new Student("aa",12);
Student s2=new Student("bb",13);
Student s3=new Student("cc",14);
Student s4=new Student("cc",14);
//添加元素
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
//遍历集合
for(Student s:hs){
System.out.println(s.getUsername()+"---"+s.getAge());
}
}
}
结果:
cc---14
bb---13
aa---12