zoukankan      html  css  js  c++  java
  • Comparable与Comparator比较分析

    Comparable与Comparator是两个接口,用来比较一个类的两个对象的大小、排序。

    可以简单理解成,Comparable帮助创建类的内部比较器,Comparator帮助用来创建类的外部比较器。

    1.Comparable

    Comparable在lang包中,使用期不需要import。

    使用方法是在类的创建中,实现Comparable接口(实现接口时需要表明泛型),并根据需要重新Comparable的compareTo()方法。

    eg:

    public class Person implements Comparable<Person>{

    private int age;

    private String name;

    public Person(int age,String name){

    this.age=age;

    this.name=name;

    }

    }

    //根据名字进行比较

    public int compareTo(Person person){
    return this.name.compareTo(person);

    }

    2.Comparator

    Comparator接口在java.util包中,使用时需要引进。

    使用方法是在类外部创建一个比较器类,该比较器类需要实现Comparator接口(实现接口时需要表明泛型),并根据需要重写compare()方法。

    eg:

    public class Person{

    private int age;

    private int name;

    public Person(int age,String name){

    this.age=age;

    this.name=name;

    }

    }

    //在外部创建一个比较器,升序比较器

    public class PersonComparator1 implements Comparator<Person>{

    int compare(Person p1,Person p2){

    return p1.age-p2.age;

    }

    //在外部创建一个比较器,降序比较器

    public class PersonComparator2 implements Comparator<Person>{

    int compare(Person p1,Person p2){

    return p2.age-p1.age;//只需调换一下顺序

    }

    这样就可以根据需要使用内部比较器和外部比较器了。

    List<Person> list=new ArrayList<Person>();

    list.add(new Person(12,"aaa"));

    list.add(new Person(12,"bbb"));

    list.add(new Person(12,"ccc"));

    System.out.println(list);//此时输出的原始顺序

    Collections.sort(list);//利用Collection的工具栏的sort方法排序

    System.out.println(list);//此时输出的根据内部比较器排序的数组

    Collections.sort(list,new  PersonComparator1());//利用Collection的工具栏的sort方法排序,注意这个排序方法要求新建外部构造器对象

    System.out.println(list);//此时输出的根据外部比较器排序的数组

  • 相关阅读:
    webpack学习笔记五
    webpack的学习使用四
    判断数组B是否为数组A的子集
    html5标签知多少
    图代文时隐藏文字的兼容实现
    负margin的移位参考线
    font-size 兼容问题
    IE6读取不到样式文件bug
    一个重构眼中的“项目管理”
    唯物 VS 唯心
  • 原文地址:https://www.cnblogs.com/hitnmg/p/9367518.html
Copyright © 2011-2022 走看看