class ADD {
public static void main(String[] args) {
Set treeSet = new TreeSet();
treeSet.add(new Student("张",21));
treeSet.add(new Student("张1",32));
treeSet.add(new Student("张1",42));
treeSet.add(new Student("张23",54));
treeSet.add(new Student("张1321",56));
treeSet.add(new Student("张1321",76));
treeSet.add(new Student("张22",64));
treeSet.add(new Student("张1331",81));
treeSet.add(new Student("张1231",99));
//添加元素
Iterator iterator = treeSet.iterator();
// 使用迭代器遍历
int i = 3;
while (i > 0){
System.out.println(iterator.next());
i--;
}
}
}
class Student implements Comparable{
String name ;//姓名
Integer mark;//分数
public Student(String name, int mark) {
this.name = name;
this.mark = mark;
}
public Student(){}
@Override
public int compareTo(Object o) {
if (o instanceof Student){//判断o是否是Student类的实例
Student student = (Student) o;//强转
if (this.mark.compareTo(student.mark) > 0){
//上面这个IF语句是返回1的,则代表按升序排
return -1;//返回负1则代表按降序排
//CompareTo是按照-1,1,0来确定元素之间的大小的。
}
}
return 0;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", mark=" + mark +
'}';
}
}
运行结果: