//学生类Student定义，并实现了Comparable接口，重写了compareTo()方法
package ch09_07;
public class Student implements Comparable<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 String toString() {// 重写toString方法
		return "学号：" + sno + ",姓名：" + sname + ",分数：" + score;
	}
	//以学号大小衡量两个Student对象的大小
	public int compareTo(Student student) {
		return this.sno.compareTo(student.sno);
	}
}
//主类，测试不同的比较规则，对TreeSet集合元素的存储排序情况
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class Ex9_7 {
	public static void main(String[] args) {
		Set<Student> treeSet1 = new TreeSet<Student>();
		Student student1 = new Student("20170001", "张三", 90);
		Student student2 = new Student("20170003", "王五", 78);
		Student student3 = new Student("20170002", "李四", 85);
		treeSet1.add(student1);
		treeSet1.add(student2);
		treeSet1.add(student3);
		System.out.println("按照学号升序排列student对象：");
		for (Student student : treeSet1) {// 遍历集合元素
			System.out.println(student);
		}
		//创建TreeSet时指定了比较器（覆盖String默认比较规则），匿名类方式定义
		Set<String> treeSet2 = new TreeSet<String>(new Comparator<String>() {
			public int compare(String s1, String s2) {
				return s2.length() - s1.length();
			}
		});
		treeSet2.add("abcdef");
		treeSet2.add("abc");
		treeSet2.add("abcd");
		System.out.println("------------------------------------------");
		System.out.println("按照字符串长度降序排列字符串：");
		for (String s : treeSet2) {// 遍历集合元素
			System.out.println(s);
		}
	}
}

