java Comparator和Comparable(比较器)

Comparable: 一个类实现了Camparable接口则表明这个类的对象之间是可以相互比较的,这个类对象组成的集合就可以直接使用sort方法排序,sort方法调用compareTo()方法里定义的方法进行排序,Comparable的缺点是只能按一种方式排序

package object;
import java.util.*;
public class Comparator1 implements Comparable<Comparator1>{    
    public int i;
    public Comparator1(int i){ 
        this.i = i;
        }
    @Override
    public int compareTo(Comparator1 o) //
    {
        
      return this.i>o.i?1:-1;
    }

    public static  void sort(int[] i)
    {
        
    }
    public static void main(String[] args)
    { 
        Comparator1[] c1 = new Comparator1[]
                {
                   new Comparator1(9),
                   new Comparator1(2),
                   new Comparator1(0),
                   new Comparator1(4),
                   new Comparator1(5),
                };
        Arrays.sort(c1);
        System.out.println(Arrays.toString(c1));
        List<Integer> list = new ArrayList<Integer>(Arrays.asList(1,2,6,2,76));
        //Collections.sort(list);
        //System.out.println(list);
    }
    public String toString()
    {
        return "Comparator1 = " + i;
    }
}

 

posted @ 2019-01-16 21:11  江期玉  阅读(302)  评论(0编辑  收藏  举报