1. 程式人生 > 其它 >定義Dog陣列並通過介面排序-方法1/2

定義Dog陣列並通過介面排序-方法1/2

方法一:

package com.iit.demo;

import java.util.Arrays;
import java.util.Comparator;

// MyComparator類有一個能力(實現了介面 = has一種能力)
// 對兩個Dog物件進行判斷:按age屬性。
class MyComparator implements Comparator<Dog>{
    @Override
    public int compare(Dog o1, Dog o2) {
        return o2.getAge()-o1.getAge();
    }
}

public class DemoArray {
    public static void main(String[] args) {
        Dog[] dogs = new Dog[5];
        int index = 0;
        dogs[index++] = new Dog("大黑1",15);
        dogs[index++] = new Dog("大黑2",13);
        dogs[index++] = new Dog("大黑3",11);
        dogs[index++] = new Dog("大黑4",9);
        dogs[index++] = new Dog("大黑5",3);

        //方法一
        //Arrays.sort(dogs,new MyComparator());
        //方法二 匿名內部類
        /*
        Arrays.sort(dogs, new Comparator<Dog>() {
            @Override
            public int compare(Dog o1, Dog o2) {
                return o1.getAge()-o2.getAge();
            }
        });
        //*/
        //方法三:用lambda優化 - 流行
        Arrays.sort(dogs, (o1, o2) -> o1.getAge()-o2.getAge());

        for(Dog d:dogs){
            System.out.println(d);
        }

    }
}
package com.iit.demo;

public class Dog {
    private String name;
    private int age;

    public Dog(){}

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        
this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Dog{" + "name='" + name + '\'' + ", age=" + age + '
}'; } }