【问题标题】:Comprator sorting one object always on top比较器总是对一个对象进行排序
【发布时间】:2014-10-06 05:37:44
【问题描述】:

我有一个要求,当对对象列表进行排序时,我想要一个对象按顺序排在第一位。这是对象列表,当使用一些通用比较器进行排序时,我希望列表中始终排在橙色水果对象的首位,我该如何使用比较器来做到这一点?

    Fruit pineappale = new Fruit("Pineapple", "Pineapple description"); 
    Fruit apple = new Fruit("Apple", "Apple description"); 
    Fruit orange = new Fruit("Orange", "Orange description"); 
    Fruit banana = new Fruit("Banana", "Banana description"); 


    List<Fruit> fruits = new ArrayList<Fruit>();

    fruits.add(pineappale);
    fruits.add(apple);
    fruits.add(orange);
    fruits.add(banana);

    Collections.sort(fruits, "some compator object"); 

    public class Fruit {

    private String fruitName;
    private String fruitDesc;


    public Fruit(String fruitName, String fruitDesc) {
        super();
        this.fruitName = fruitName;
        this.fruitDesc = fruitDesc;
    }

    public String getFruitName() {
        return fruitName;
    }
    public void setFruitName(String fruitName) {
        this.fruitName = fruitName;
    }
    public String getFruitDesc() {
        return fruitDesc;
    }
    public void setFruitDesc(String fruitDesc) {
        this.fruitDesc = fruitDesc;
    }   

}

【问题讨论】:

  • 别忘了重写 toString 方法

标签: java


【解决方案1】:

回复Collections.sort(fruits, "some compator object");

与:

    Collections.sort(fruits, new Comparator<Fruit>() {

        @Override
        public int compare(Fruit o1, Fruit o2) {
            if (o1.getFruitName() != null && o1.getFruitName().equalsIgnoreCase("orange")){
                return -1;
            }

            if (o2.getFruitName() != null && o2.getFruitName().equalsIgnoreCase("orange")){
                return 1;
            }

            return o1.getFruitName().compareTo(o2.getFruitName());
        }
    }); 

【讨论】:

  • 当我使用 Arrays.parallelSort 我得到不同的答案你知道为什么吗?
  • @KickButtowski 不抱歉。
  • 这被破坏了,因为它会产生不一致的结果,例如如果两个名称都是"orange"。此外,这些null-check 没有任何意义,因为在最后一行中使用的名称没有null-check。
  • @h 你能善待并发布你对此事的答案吗?请提供解释
猜你喜欢
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多