Java??Comparator?????Comparable????????
???????????? ???????[ 2014/4/16 9:14:03 ] ????????Java ???
????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;
}
}
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11