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>

sales@spasvo.com