简单HashSet应用,对于学生信息的增加和删除
/**
* 描述: 封装学生类
* 类名: Student
* 作者: wangpeng
* 时间: 2018年8月11日下午7:44:20
*/
public class Student {
private String sId;
private String sName;
private String sHobby;
public Student() {
}
public Student(String sId, String sName, String sHobby) {
this.sId = sId;
this.sName = sName;
this.sHobby = sHobby;
}
public String getsId() {
return sId;
}
public void setsId(String sId) {
this.sId = sId;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public String getsHobby() {
return sHobby;
}
public void setsHobby(String sHobby) {
this.sHobby = sHobby;
}
@Override
public String toString() {
return "Student [sId=" + sId + ", sName=" + sName + ", sHobby=" + sHobby + "]";
}
}
public class TestStudenst {
private HashSet<Student> stuHash=new HashSet<Student>();
@Test
public void add_stuHashSet() {
Scanner in=new Scanner(System.in);
boolean f=true;
while(f) {
Student stu=new Student();
System.out.print("输入学号:");
stu.setsId(in.next());
System.out.print("输入姓名:");
stu.setsName(in.next());
System.out.print("输入爱好:");
stu.setsHobby(in.next());
stuHash.add(stu);
System.out.print("是否继续添加(是yes/否no):");
if(in.next().equals("no"))
f=false;
}
System.out.println("学生信息:");
Iterator<Student> iter=stuHash.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
iter=stuHash.iterator();
System.out.print("输入要删除的学生姓名:");
String str=in.next();
while(iter.hasNext()) {
Student s=iter.next();
if(s.getsName().equals(str))
iter.remove();
}
System.out.println("删除后学生信息:");
iter=stuHash.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
}
}