集合框架-比较器(Comparator接口)

一、基本含义

类型:接口。
含义:可比较的。
比较规则:临时比较规则。像工具类。
必须实现方法:int compare()。负数(小)零(相等)正数(大)。

二、实例——实现Comparator接口

public class Course implemants Comparator{
  private String id;
  private String name;
  public Course(){
  }
  public Course(String id,String name){
    this.id = id;
    this.name = name;
  }
  @Override
  public int compare(Course1 o1, Course2 o2){
    return o1.name.compare(o2.name); // 此时为升序排列。
    //return o2.name.compare(o1.name); // 此时为降序排列。
  }
}

调用**Collection.sort()**方法:

List<Course> courseList = new ArrayList<Course>();
Course[] courseArray = {new Course("1","语文"),new Course("3","英语"),new Course("2","数学")};
courseArray.addAll(Arrays.asList(courseList));
Collections.sort(courseArray, new Course());

猜你喜欢

转载自blog.csdn.net/lizengbao/article/details/86747553