天道不一定酬所有勤
但是,天道只酬勤
Hollis出品的全套Java面试宝典不来了解一下吗?

list的排序

Hollis出品的全套Java面试宝典不来了解一下吗?

第一种方法,就是list中对象实现Comparable接口

public class Person implements Comparable<Person> {
    private String name;
    private Integer order;

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the order
     */
    public Integer getOrder() {
        return order;
    }

    /**
     * @param order
     *            the order to set
     */
    public void setOrder(Integer order) {
        this.order = order;
    }

    @Override
    public int compareTo(Person arg0) {
        return this.getOrder().compareTo(arg0.getOrder());
    }

}

第二种方法,就是在重载Collections.sort方法

Collections.sort(listA, new Comparator<Person>() {
            public int compare(Person arg0, Person arg1) {
                return arg0.getOrder().compareTo(arg1.getOrder());
            }
        });

Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract!

赞(0)
如未加特殊说明,此网站文章均为原创,转载必须注明出处。HollisChuang's Blog » list的排序
Hollis出品的全套Java面试宝典不来了解一下吗?

评论 抢沙发

HollisChuang's Blog

联系我关于我