比较器总是在顶部排序一个对象

时间:2014-10-06 05:37:44

标签: java

我要求在对对象列表进行排序时,我首先想要一个对象。这是对象列表,当使用一些通用比较器排序时,我想在列表中首先使用橙色水果对象,我该如何使用比较器呢?

    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;
    }   

}

1 个答案:

答案 0 :(得分:3)

Repleace 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());
        }
    });