Java??Comparator?????Comparable????????
???????????? ???????[ 2014/4/16 9:14:03 ] ????????Java ???
???????????????????comparator??????API?п???鵽??TreeSet?????????????????TreeSet(Comparator<? super E> c)???????????????????????????????????????TreeSet????????????????????????????????е?compare???????б???
/* ????????????????????????
* ?????????TestComparator.java
* ? ??
* ????????Studnet??.
* Student??????????????????
* ???TreeSet?????????Comparator????????????????
*/
import java.util.*;
public class TestComparator{
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>(new StudentComparator());
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{
private int id;
private String name;
public Student(String name??int id){
this.name = name;
this.id = id;
}
public String getName(){
return name;
}
public int getId(){
return id;
}
}
class StudentComparator implements Comparator<Student>{
public int compare(Student stu1??Student stu2){
//??????????????????????
if(stu1.getId() == stu2.getId() ){
return stu1.getName().compareTo(stu2.getName());
}else
return stu1.getId() - stu2.getId();
}
}
????TreeSet??TreeMap?е?????????
????TreeSet??TreeMap??????????????????????????????????????????????????е??????????????????????????ж????????????????????????????????????????????????????ν???????????????????????????????????TreeMap??put??key?????????key??????б???????TreeSet??add??E?????????elements??????б?????????cannot be cast to java.lang.Comparable?????????????????????????????????????????TreeSet????TreeMap????????????????Comparator?????????????????TreeMap?????????elements???comparable????????????TreeSet?????key????comparable????
<p style="color:rgb(69??69??69); margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:tahoma??helvetica??arial; font-size:14px; line-height:21px"></p><pre code_snippet_id="293144" snippet_file_name="blog_20140415_3_8923425" style="color:rgb(69??69??69)"></pre>
<pre style="color:rgb(69??69??69)"></pre>
<pre></pre>
<pre></pre>
<pre></pre>
<pre></pre>
<pre></pre>
<pre></pre>
<pre></pre>
??????
???·???
??????????????????
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