首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

对象依照某属性升序,降序

2013-03-16 
对象按照某属性升序,降序只是写了按照对象里面的id排序,如果按照其余的字段升降序也可以实现。/** * 个人信

对象按照某属性升序,降序

只是写了按照对象里面的id排序,如果按照其余的字段升降序也可以实现。

/** * 个人信息排序 * @author wWX154783 *  */public class PersonSort{    public static void main(String[] args)    {        List<Person> list = new ArrayList<Person>();        for (int i = 0; i < 10; i++)        {            Person person = new Person();            person.setId(new Random().nextInt(50));            list.add(person);        }        System.out.println("原始:\t" + list);        Collections.sort(list, new PersonOrderByIdAsc());        System.out.println("升序:\t" + list);        Collections.sort(list, new PersonOrderByIdDesc());        System.out.println("降序:\t" + list);    }}/* 人 */class Person implements Comparator<Person>{    private int id;    private int age;    private String name;    private String sex;    private String address;    public int compare(Person o1, Person o2)    {        return 0;    }    public int getId()    {        return id;    }    public void setId(int id)    {        this.id = id;    }    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;    }    public String getSex()    {        return sex;    }    public void setSex(String sex)    {        this.sex = sex;    }    public String getAddress()    {        return address;    }    public void setAddress(String address)    {        this.address = address;    }    @Override    public String toString()    {        return "id=" + this.id;    }}/* 按照person id升序 */class PersonOrderByIdAsc extends Person{    @Override    public int compare(Person o1, Person o2)    {        if (o1.getId() > o2.getId())        {            return 1;        }        else if (o1.getId() < o2.getId())        {            return -1;        }        else        {            return 0;        }    }}/* 按照person id降序 */class PersonOrderByIdDesc extends Person{    @Override    public int compare(Person o1, Person o2)    {        if (o1.getId() < o2.getId())        {            return 1;        }        else if (o1.getId() > o2.getId())        {            return -1;        }        else        {            return 0;        }    }}


1楼adam_zs昨天 16:31
[code=java]n输出结果:n原始:t[id=14, id=32, id=43, id=7, id=12, id=22, id=38, id=36, id=36, id=26]n升序:t[id=7, id=12, id=14, id=22, id=26, id=32, id=36, id=36, id=38, id=43]n降序:t[id=43, id=38, id=36, id=36, id=32, id=26, id=22, id=14, id=12, id=7]n[/code]

热点排行