示例代码:
package JavaReview.src;
public class StudentEntity {
private int studentId;
private String name;
private String gender;
private String adress;
public StudentEntity(int studentId, String name, String gender, String adress) {
this.studentId = studentId;
this.name = name;
this.gender = gender;
this.adress = adress;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
@Override
public String toString() {
return "{" +
"学号:" + studentId +
", 姓名:" + name +
", 性别:" + gender +
", 家庭住址:" + adress +
'}';
}
public int hashCode(){
return this.studentId;
}
public boolean equals(Object obj){
if(obj==this)
return true;
if(obj.getClass() == StudentEntity.class){
StudentEntity stu_obj =(StudentEntity) obj;
return stu_obj.getStudentId() == this.studentId;
}
return false;
}
}
package JavaReview.src;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class StudentOperator {
public static void main(String[] args) {
StudentEntity stu1= new StudentEntity(01,"张三","男","河北石家庄");
StudentEntity stu3= new StudentEntity(03,"李四","女","河南驻马店");
StudentEntity stu2= new StudentEntity(02,"王五","男","北京五道口");
StudentEntity stu4= new StudentEntity(01,"翠花","女","河北石家庄");
Set hashSet = new HashSet();
hashSet.add(stu1);
hashSet.add(stu2);
hashSet.add(stu3);
hashSet.add(stu4);
for (Object obj: hashSet) {
System.out.println(obj);
}
System.out.println("=================");
Iterator iterator = hashSet.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("=================");
System.out.println(hashSet);
for (Object obj: hashSet) {
StudentEntity studentEntity =(StudentEntity) obj;
System.out.print("姓名: "+studentEntity.getName()+" ");
System.out.println("家庭住址: "+studentEntity.getAdress());
System.out.println("=================");
String stuName = "李四";
boolean flag =false;
String result =null;
for (Object obj: hashSet) {
StudentEntity studentEntity =(StudentEntity) obj;
if(studentEntity.getName().equals(stuName)){
flag=true;
result = studentEntity.toString();
}else{
flag=false;
}
}
if(flag){
System.out.println("找到了!");
System.out.println(result);
}else{
System.out.println("没找到!");
}
}
}
}
}
- 执行结果
![](https://i-blog.csdnimg.cn/blog_migrate/c45e607a7f8c850e0e6dd3b543cd97f2.png)