我有要求,當排序對象的列表時,我想要一個對象的順序。這裏是對象的列表,當使用某個通用比較器進行排序時,我總是希望列表中的第一個橙色水果對象,我如何使用比較器做到這一點?Comprator排序一個對象總是在頂部
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方法 – 2014-10-06 05:59:15