package com;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDome1 {
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<Student>(new MyComparator());
//定义类非自然数进行排序,需要实现Comparator接口里面的compare方法,new MyComparator(),来标识排序的方法
Student s1 = new Student(10);
Student s2 = new Student(20);
Student s3 = new Student(30);
Student s4 = new Student(40);
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
for(Iterator<Student> iter = set.iterator(); iter.hasNext(); ){
System.out.println(iter.next().scores);
}
System.out.println("minimum value: "+ Collections.min(set,new MyComparator()).scores);//最小值
System.out.println("maximum value: "+ Collections.max(set,new MyComparator()).scores); //最大值
}
}
class Student{
int scores;
public Student(int scores){
this.scores = scores;
}
}
class MyComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {// o1>o2 返回1,o1<o2 返回-1 o1=o2 返回0
return o2.scores - o1.scores;
}
}