//Student类，并重写了hashCode()方法、equals()方法和toString()方法
package ch09_06;
public class Student {
	private String sno;    //学生学号
	private String sname;  //姓名
	private int score;      //分数
	public Student() {}
	public Student(String sno, String sname, int score) {
		this.sno = sno;
		this.sname = sname;
		this.score = score;
	}
	public String getSno() {return sno;}
	public void setSno(String sno) {this.sno = sno;	}
	public String getSname() {return sname;}
	public void setSname(String sname) {this.sname = sname;}
	public int getScore() {return score;}
	public void setScore(int score) {this.score = score;}
	@Override
	public int hashCode() {//重写hashCode方法
		return sno.hashCode();
	}
	@Override
	public boolean equals(Object obj) {//重写equals方法
		if (obj instanceof Student) {
			return this.getSno().equals(((Student) obj).getSno());
		}
		return false;
	}
	@Override
	public String toString() {// 重写toString方法
		return "学号：" + sno + ",姓名：" + sname + ",分数：" + score;
	}
}


//主类，测试Set集合的元素添加与遍历操作
package ch09_06;
import java.util.HashSet;
import java.util.Set;
public class HashSetStudent {
	public static void main(String[] args) {
		Set<Student> hashSet = new HashSet<Student>();
		Student student1 = new Student("20170001", "张三", 90);
		Student student2 = new Student("20170002", "李四", 85);
		Student student3 = new Student("20170003", "王五", 78);
		Student student4 = new Student("20170001", "赵六", 78);//同student1学号相同
		hashSet.add(student1);
		hashSet.add(student2);
		hashSet.add(student3);
		hashSet.add(student4);//添加失败
		for (Student student : hashSet) {//遍历集合元素
			//自动调用toString()方法，将对象转换为字符串，输出
			System.out.println(student); 
		}
	}
}
