Comparable是排序接口。若一个类实现了Comparable接口,就意味着该类支持排序。实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或Arrays.sort进行自动排序。
此外,实现此接口的对象可以用作有序映射中的键或有序集合中的集合,无需指定比较器。该接口定义如下:
package java.lang;
import java.util.*;
public interface Comparable<T> {
public int compareTo(T o);
}
//下面例子
import java.util.Arrays;public class Person implements Comparable<Person>
{String name;int age;public Person(String name, int age){super();this.name = name;this.age = age;}public String getName(){return name;}public int getAge(){return age;}//@Overridepublic int compareTo(Person p){return this.age-p.getAge();}public static void main(String[] args){Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};System.out.println("排序前");for (Person person : people){System.out.print(person.getName()+":"+person.getAge());}int a[]=new int[] {1,2,3};Arrays.sort(a);//Arrays.sort只能排序数组,对于类数组,用到Comparable接口里的compareTo函数,顺带一提comparaTo须重定义,否则默认字符串Ascii比较。Arrays.sort(people);System.out.println("\n排序后");for (Person person : people){System.out.print(person.getName()+":"+person.getAge());}}
}
Comparator是比较接口,我们如果需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口),那么我们就可以建立一个“该类的比较器”来进行排序,这个“比较器”只需要实现Comparator接口即可。也就是说,我们可以通过实现Comparator来新建一个比较器,然后通过这个比较器对类进行排序。该接口定义如下:
package java.util; public interface Comparator<T>{int compare(T o1, T o2);boolean equals(Object obj);}
注意:1、若一个类要实现Comparator接口:它一定要实现compare(T o1, T o2) 函数,但可以不实现 equals(Object obj)
import java.util.Arrays;
import java.util.Comparator;class PersonCompartor implements Comparator<person1>
{@Overridepublic int compare(person1 o1, person1 o2){return o1.getAge()-o2.getAge();}
}
public class person1
{String name;int age;public person1(String name, int age){super();this.name = name;this.age = age;}public String getName(){return name;}public int getAge(){return age;}public static void main(String[] args){person1[] people=new person1[]{new person1("xujian", 20),new person1("xiewei", 10)};System.out.println("排序前");for (person1 person : people){System.out.print(person.getName()+":"+person.getAge());}//同Person类,Arrays.sort()需要协同比较器Comparator;Arrays.sort(people,new PersonCompartor());System.out.println("\n排序后");for (person1 person : people){System.out.print(person.getName()+":"+person.getAge());}}
}
另外Comparable可以在一个函数单独做一个类,里面有compareTo()函数
import java.util.Date;
public class lab{public static Comparable max(Comparable a[]){Comparable mix=a[0];for(int i=1;i<a.length;i++)if(mix.compareTo(a[i])<0)mix=a[i];return mix;}public static void main(String args[]){Comparable a[][]=new Comparable[][] {{"a","b","c","d","e","f","h","i","k","j"},{1,2,3,4,5,6,7,8,9,10},{new Date(),new Date(),new Date(),new Date(),new Date(),new Date(),new Date(),new Date(),new Date(),new Date()}};for(int i=0;i<a.length;i++)System.out.println("max:"+max(a[i]));}
}