public interface Comparable<T>{
int compareTo(T o);
}
接口强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较方法。
实现此接口的对象列表(和数组)可以通过Collections.sort(new person());.Arrays.sort(new person());.
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;
}
@Override
public 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());
}
Arrays.sort(people);
System.out.println("\n排序后");
for (Person person : people)
{
System.out.print(person.getName()+":"+person.getAge());
}
}
}
public interface Comparator<T>{
int compare(T o1,T o2);
}
强行对某个对象 collection 进行整体排序 的比较函数。实现此接口的对象列表(和数组)可以通过Collections.sort(new person(),new personComparator());.Arrays.sort(new person(),new personComparator());.
public class PersonCompartor implements Comparator<Person>
{
@Override
public int compare(Person o1, Person o2)
{
return o1.getAge()-o2.getAge();
}
}
public class 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;
}
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());
}
Arrays.sort(people,new PersonCompartor());
System.out.println("\n排序后");
for (Person person : people)
{
System.out.print(person.getName()+":"+person.getAge());
}
}
}
总结:Comparable相当于内部比较器,Comparator相当于外部比较器。
博客介绍了Comparable和Comparator两个接口。Comparable接口可对实现它的类对象进行自然排序,实现该接口的对象列表和数组可通过特定方法排序;Comparator接口是对对象collection进行整体排序的比较函数,实现该接口的对象列表和数组排序时需传入比较器。总结指出Comparable是内部比较器,Comparator是外部比较器。

被折叠的 条评论
为什么被折叠?



