码迷,mamicode.com
首页 > 编程语言 > 详细

Java实现根据属性排序输出对象

时间:2016-02-02 14:44:58      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

package com.wms;

import java.util.Arrays;

public class DogAgeSort {

    public static void main(String[] args) {

        Dog[] dogs = {new Dog("小黄",2), new Dog("小绿",1), new Dog("小黑",3) , new Dog("小红",6)};
        Arrays.sort(dogs, new DogComparator());
        
        for(Dog dog: dogs){
            System.out.println(dog);
        }
        
    }

}
package com.wms;

public class Dog {

    private String name;
    private int age;
    
    
    public Dog() {}
    public Dog(String name, int age) {
        super();
        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 + "]";
    }
    
}
package com.wms;

import java.util.Comparator;

public class DogComparator implements Comparator<Dog>{

    public int compare(Dog o1, Dog o2) {
        if(o1.getAge()<o2.getAge()){
            return -1;
        }else if(o1.getAge()>o2.getAge()){
            return 1;
        }else{
            return 0;
        }
    }




}

 

Java实现根据属性排序输出对象

标签:

原文地址:http://www.cnblogs.com/sweetstar86/p/5176901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!