????4.???
???????????????????? ??Comparable ???? ?????Comparable ???????????????????????????????????????? ??Comparator ?????????????????? ????????????????????? ??????????????????????????????????????????????????С??? ??????Comparator ???????????????????????????????????????????Щ???????????????????????????????
????/----------------------------------------------?????------------------------------------------------/
????java???Comparable???????
??????????????????????????????????????????????????????????
??????????
????????????Student?????Comparable?????y??????????????????Student?????????????????????TreeSet??????Student??????????????????????????????????????????????д???????????£?????????????????????????????????
/*  ????????????????????????
*  ?????????TestComparable.java
*  ?  ??
*      ????????Studnet?????Comparable????
*      Student??????????????????
*      ???TreeSet??????????????????
*/
import java.util.*;
public class TestComparable{
public static void main(String[] args){
Student s1 = new Student("С??"??1);
Student s2 = new Student("????"??2);
Student s3 = new Student("????"??3);
Student s4 = new Student("????"??4);
Student s5 = new Student("????"??5);
Set<Student> set = new TreeSet<Student>();
set.add(s5);
set.add(s3);
set.add(s2);
set.add(s4);
set.add(s1);
Iterator<Student> it = set.iterator();
System.out.println("??? "+"???????");
while(it.hasNext()){
Student s = it.next();
System.out.println(s.getId()+" "+s.getName());
}
}
}
//???????????class Student implements Comparable?????????
class Student implements Comparable<Student>{
private int id;
private String name;
public Student(String name??int id){
this.name = name;
this.id = id;
}
public int compareTo(Student stu){//??????????????????????
if(this.getId() == stu.getId() ){
return this.getName().compareTo(stu.getName());
}else
return this.getId() - stu.getId();
}
public String getName(){
return name;
}
public int getId(){
return id;
}
}