标签:
接口Comparable和Comparator的区别和关系
1).两者都是实现集合中元素的比较、排序;
2).Comparable是集合内部定义方法实现排序,Comparator是集合外部实现排序
3).Comparator接口在java.util下,Comparable接口在java.lang下;
通常自定义类加入如List等容器中能够排序,可以实现Comparable接口,在用Collections.sort(List<T> list, Comparator<? super T> c)排序时,如果不指定Comparator,那么就会按照自然顺序(Comparable的排序方式)进行排序。如API的注释:
Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator
Sorts the specified list into ascending order, according to the <i>natural ordering</i> of its elements
而Comparator 是一个专用的比较器,当这个对象不支持自比较或者自比较函数不能满足你的要求时,你可以写一个比较器来完成两个对象之间大小的比较。
例如:你想对整数采用绝对值大小来排序,Integer 是不符合要求的,你不需要去修改 Integer 类(实际上你也不能这么做)去改变它的排序行为,只要使用一个实现了 Comparator 接口的对象来实现控制它的排序就行了。
常用类如String、Integer可以完成比较大小的操作,其原因就是实现了Comparable接口
package com.pachira.B; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Scanner; public class SortCount { private static String TEXT = "data/words.count"; private static String charset = "gbk"; public static void main(String[] args) { if(args.length < 2){ System.err.println("Usage: SortCount words.count charset[gbk/utf8]"); System.exit(-1); } TEXT = args[0]; charset = args[1]; SortCount d = new SortCount(); d.sort(); } private void sort() { try { Scanner in = new Scanner(new FileInputStream(TEXT), charset); List<Word> words = new ArrayList<Word>(); while(in.hasNext()){ String sent = in.nextLine(); String[] list = sent.split("\t"); if(list.length >= 2){ try { words.add(new SortCount.Word(list[0], Integer.parseInt(list[1]))); } catch (Exception e) { continue; } } } in.close(); Collections.sort(words, new Comparator<Word>() { @Override public int compare(Word o1, Word o2) { int first = o2.count.compareTo(o1.count); if(first == 0){ return o2.name.compareTo(o1.name); } return first; } }); for(Word word: words){ System.out.println(word); } } catch (Exception e) { System.err.println(e.getMessage()); } } class Word { private String name; private Integer count; public Word(String name, Integer count) { this.name = name; this.count = count; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(this.name + "\t" + this.count); return sb.toString(); } } }
【Java基础】接口Comparable和Comparator的区别和关系
标签:
原文地址:http://www.cnblogs.com/ariesblogs/p/4205849.html