常用的比较器:实现方式Compareable和Comparator

class Dog{  
    int size;  
    int weight;  
   
    public Dog(int s, int w){  
        size = s;  
        weight = w;   
    }  
}  
   

 

 

目的:对于Dog对象作为元素所组成的数组进行对象属性的自定义排序

一、外部比较器 Comparator:优点是不对源代码造成影响

class DogSizeComparator implements Comparator<Dog>{  
   
    @Override  
    public int compare(Dog o1, Dog o2) {  
        return o1.size - o2.size;  
    }  
} 


public class ArraySort {  
   
    public static void main(String[] args) {  
        Dog d1 = new Dog(2, 50);  
        Dog d2 = new Dog(1, 30);  
        Dog d3 = new Dog(3, 40);  
   
        Dog[] dogArray = {d1, d2, d3};  
        printDogs(dogArray);   
        Arrays.sort(dogArray, new DogSizeComparator());     
        printDogs(dogArray);  
    }  
   
    public static void printDogs(Dog[] dogs){  
        for(Dog d: dogs)  
            System.out.print("size="+d.size + " weight=" + d.weight + " ");  
   
        System.out.println();  
    }  
}  

 

  1、编写一个外部比较器:实现Comparator泛型为需要排序对象的类,并重写

compare(Dog o1, Dog o2)方法,如果进行正序的排序,那返回值为o1.属性-o2.属性,属性为根据此排序的参考

  2、通过Arrays.sort(dogArray, new DogSizeComparator());参数为需要排序的对象的数组和对应比较器,进行排序

二、内部比较器Compareable:对象所属的类需要实现Compareable接口

  

public class Person implements Comparable<Person>
{
    String name;
    int age;
    public Person(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    @Override
    public int compareTo(Person p)
    {
        return this.age-p.getAge();
    }
    public static void main(String[] args)
    {
        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};
        System.out.println("排序前");
        for (Person person : people)
        {
            System.out.print(person.getName()+":"+person.getAge());
        }
        Arrays.sort(people);
        System.out.println("\n排序后");
        for (Person person : people)
        {
            System.out.print(person.getName()+":"+person.getAge());
        }
    }
}

  1所需要排序数组的元素对象所属的类 必须要实现Compareable接口并重写 compareTo()方法 正序返回this.属性-参数对象.属性 反序则取反。

  2对于该对象的数组使用Arrays.sort(people)进行排序

 

posted @ 2017-10-15 10:58  羊不吃草  阅读(1254)  评论(0编辑  收藏  举报