2014-10-06 36 views
2

我有要求,當排序對象的列表時,我想要一個對象的順序。這裏是對象的列表,當使用某個通用比較器進行排序時,我總是希望列表中的第一個橙色水果對象,我如何使用比較器做到這一點?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; 
    } 

} 
+0

不要忘了覆蓋toString方法 – 2014-10-06 05:59:15

回答

2

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

當我用Arrays.parallelSort我得到不同的答案你有任何想法,爲什麼? – 2014-10-06 06:03:24

+0

@KickButtowski沒有抱歉。 – Jens 2014-10-06 06:14:04

+0

http://stackoverflow.com/questions/26210842/different-output-from-arrays-parallelsort-and-collections-sort看看它,如果你喜歡 – 2014-10-06 06:18:11