HashSet集合案例实操
练习:HashSet集合存储自定义老师对象并遍历
要求:对象的成员变量值相同视为同一个对象
//Teacher.java
package com.set.demo2;
public class Teacher {
public Teacher() {
super();
}
public Teacher(String name, int age, int weight, int height, String address) {
super();
this.name = name;
this.age = age;
this.weight = weight;
this.height = height;
this.address = address;
}
private String name;
private int age;
private int weight;
private int height;
private String address;
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;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + age;
result = prime * result + height;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + weight;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Teacher other = (Teacher) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (age != other.age)
return false;
if (height != other.height)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (weight != other.weight)
return false;
return true;
}
@Override
public String toString() {
return "Teacher [name=" + name + ", age=" + age + ", weight=" + weight + ", height=" + height + ", address="
+ address + "]";
}
}
//TeacherTest.java
package com.set.demo2;
import java.util.HashSet;
import java.util.Set;
public class TeacherSet {
public static void main(String[] args) {
Set<Teacher> set = new HashSet<Teacher>();
Teacher t1 = new Teacher("孙老师", 33, 70, 175, "北京");
Teacher t2 = new Teacher("李老师", 34, 71, 176, "北京");
Teacher t3 = new Teacher("王老师", 35, 72, 177, "北京");
Teacher t4 = new Teacher("赵老师", 36, 73, 178, "北京");
Teacher t5 = new Teacher("孙老师", 33, 70, 175, "北京");
set.add(t1);
set.add(t2);
set.add(t3);
set.add(t4);
set.add(t5);
for (Teacher teacher : set) {
System.out.println(teacher);
}
}
}
***执行结果:***
Teacher [name=李老师, age=34, weight=71, height=176, address=北京]
Teacher [name=赵老师, age=36, weight=73, height=178, address=北京]
Teacher [name=孙老师, age=33, weight=70, height=175, address=北京]
Teacher [name=王老师, age=35, weight=72, height=177, address=北京]