Comparable & Comparator简介

来源:互联网 发布:英语听力下载软件 编辑:程序博客网 时间:2024/06/05 04:03

在集合框架中,如果某个集合中的序列要使用Collections.sort()方法,则必需实现Comparable接口。

Comparable & Comparator



JAVA 集合框架的主要成员:


示例:创建一个Student类型(基本数据类型的包装类的List(集合)可直接使用Collections.sort()方法)的List,向其添加学生并通过Collections.sort()方           法排序输出。

1.创建学生类,继承Comparable接口

package imooc;import java.util.HashSet;import java.util.Set;//学生类public class Student implements Comparable<Student>{public String id;public String name;public Set<Course> courses;public Student(String id,String name){this.id=id;this.name=name;this.courses =new HashSet<Course>();}@Overridepublic int compareTo(Student o) {        //通过ID比较排序// TODO Auto-generated method stubreturn this.id.compareTo(o.id);}}
2.创建一个studentComparator类,继承Comparator接口

package imooc;import java.util.Comparator;public class studentComparator implements Comparator<Student> {@Overridepublic int compare(Student a, Student b) {   //通过姓名比较排序// TODO Auto-generated method stubreturn a.name.compareTo(b.name);}}
测试类


package imooc;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Random; //测试student类型的List   public void testStudent(){   List<Student> list3=new ArrayList<Student>();   Random random=new Random();   list3.add(new Student(random.nextInt(1000)+"","jack"));   list3.add(new Student(random.nextInt(1000)+"","anei"));   list3.add(new Student(random.nextInt(1000)+"","back"));   System.out.println("---排序前----");   for(Student s:list3){   System.out.println(s.id+" "+s.name);   }   System.out.println("---排序后----");   System.out.println("按照ID排序:");   Collections.sort(list3);   for(Student s:list3){   System.out.println(s.id+" "+s.name);   }   System.out.println("按照姓名排序:");   Collections.sort(list3,new studentComparator());   for( Student s2:list3){   System.out.println(s2.id+" "+s2.name );   }      }public static void main(String[] args) {testCollection it=new testCollection();it.testStudent();
结果:




原创粉丝点击