Comparable接口
例:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BiJiao {
public static void main(String[] args) {
Person p1=new Person("li", 18);
Person p2=new Person("li", 19);
Person p3=new Person("chen", 20);
Person p4=new Person("aa", 20);
List<Person> list = new ArrayList<>();
list.add(p4);
list.add(p2);
list.add(p3);
list.add(p1);
// 对List进行排序
Collections.sort(list);
System.out.println(list);
}
}
class Person implements Comparable<Person>{
String name;
int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "name="+name+",age="+age;
}
// 按照年龄、姓名排序
@Override
public int compareTo(Person o) {
// TODO Auto-generated method stub
int d1 = age-o.age;
int d2 = name.compareTo(o.getName());
if(d1!=0)
return d1;
else
return d2;
}
}
Comparator接口
如果某个类没有实现Comparable接口,该如何比较大小呢?我们可以新建一个类,让其实现Comparator接口
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());
}
}
}