1.Comparator接口:
定义:java特意实现的一个接口工具,用来对象排序
方法:int compare(Object t1,Object t2)
Boolean equals(Object obj)
接口定义在java.Util里面
调用Collections.sort(collection, 比较器)
2.Comparable接口:
定义:只要某个类实现了这个接口,那么这个类的所有对象都会进行整体排序
方法:int compareTo(Object T)
集合和数组都调用Collection.sort()、Arrays.sort()方法进行排序
接口定义在java.lang包里面
例子:
使用comparator:
public class StudentTest implements Comparator<Student> {
@Override
public int compare(Student arg0, Student arg1) {
// TODO Auto-generated method stub
return new String(arg0.getName()).compareTo(new String(arg1.getName()));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Student st1=new Student(40,20,"peter");
Student st2=new Student(28,5,"angel");
Student st3=new Student(35,18,"tom");
List<Student> list=new ArrayList<Student>();
list.add(st1);
list.add(st2);
list.add(st3);
System.out.println("before:");
for(Student stu:list) {
System.out.println(stu);
}
Collections.sort(list, new StudentTest());
System.out.println("after:");
for(Student stu:list) {
System.out.println(stu);
}
}
}
使用comparable:
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee e1=new Employee("emp001","张三",1800.0);
Employee e2=new Employee("emp002","李四",2500.0);
Employee e3=new Employee("emp003","王五",1600.0);
List<Employee> list=new ArrayList<Employee>();
list.add(e1);
list.add(e2);
list.add(e3);
System.out.println("排序前:");
for(Employee emp:list) {
System.out.println(emp);
}
Collections.sort(list);//排序
System.out.println("排序后:");
for(Employee emp:list) {
System.out.println(emp);
}
}
}