Comparator 和 Comparable 比较
Comparable是排序接口;若一个类实现了Comparable接口,就意味着“该类支持排序”。
而Comparator是比较器;我们若需要控制某个类的次序,可以建立一个“该类的比较器”来进行排序。
我们不难发现:Comparable相当于“内部比较器”,而Comparator相当于“外部比较器”。
Comparable位于java.lang包下,comparator位于java.util包下
实现comparable接口的类,需要重写compareTo()方法
实现comparator接口的类,需要重写compare()方法
实现Comparable接口的对象列表(和数组)可以通过 Collections.sort
(和 Arrays.sort
)进行自动排序
强行对某个对象 collection 进行整体排序的比较函数。可以将 Comparator 传递给 sort 方法(如 Collections.sort
或 Arrays.sort
),从而允许在排序顺序上实现精确控制。
实现Comparable接口的使用实例
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public class Present1 implements Comparable<Present1>{ private int num; private double price; private String name; public Present1(int num,double price,String name) { // TODO Auto-generated constructor stub this.num=num; this.price=price; this.name=name; } public static void main(String args[]){ Present1 p1=new Present1(10, 20, "手表"); Present1 p2=new Present1(15, 30, "裙子"); Present1 p3=new Present1(12, 24, "包包"); Present1 p4=new Present1(40, 40, "书"); List<Present1> list=new ArrayList<Present1>(); list.add(p1); list.add(p2); list.add(p3); list.add(p4); Collections.sort(list); for(int i=0;i<list.size();i++){ System.out.println(list.get(i).num); } } @Override public int compareTo(Present1 o) { // TODO Auto-generated method stub return this.num-o.num; } }
实现comparator接口的实例:
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Present2 { public int num; public double price; public String name; public Present2(int num,double price,String name) { // TODO Auto-generated constructor stub this.num=num; this.price=price; this.name=name; } public static void main(String args[]){ Present2 p1=new Present2(10, 20, "手表"); Present2 p2=new Present2(15, 15, "裙子"); Present2 p3=new Present2(12, 24, "包包"); Present2 p4=new Present2(40, 23, "书"); List<Present2> list=new ArrayList<Present2>(); list.add(p1); list.add(p2); list.add(p3); list.add(p4); Collections.sort(list, new numComparator()); for(int i=0;i<list.size();i++){ System.out.println(list.get(i).num+" -"+list.get(i).name); } Collections.sort(list, new priceComparator()); for(int i=0;i<list.size();i++){ System.out.println(list.get(i).price+" -"+list.get(i).name); } } } class numComparator implements Comparator<Present2>{ @Override public int compare(Present2 o1, Present2 o2) { // TODO Auto-generated method stub return o1.num-o2.num; } } class priceComparator implements Comparator<Present2>{ @Override public int compare(Present2 o1, Present2 o2) { // TODO Auto-generated method stub return new Double(o1.price).compareTo(new Double(o2.price)); } }