2011-12-11 40 views
-7

例如,我有兩個對象:排序(構造函數)在Java中

Icecream ice1 = new Icecream(vanilla, newDate(11, 09, 09)); 
Icecream ice2 = new Icecream(choko, newDate(10, 08, 08)); 
// where first argument is a String and second argument is a Date 

我怎麼能打印出來,使他們從最早開始的日期進行排序? (toStrign方法已經配置)

輸出sholud是:

Vanilla, 10-08-08 
Vanilla, 11-09-09 

謝謝!

+2

http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html - Oracle教程是搜索「java對象排序」時的第三個鏈接 –

+2

搜索論壇。有數百個關於如何實現Comparable接口或創建自定義比較器的示例。 – camickr

回答

1

您可以通過實現Comparator接口定義您IceCream類自然排序。

public class IceCream implements Comparator{ 
    // ... 
    final String name; 
    final Date date; 
    public Icecream(String name, Date date){ 
     this.name = name; 
     this.date = date; 
    } 
    public int compare(Object o1, Object o2) { 
     return ((IceCream)o1).date.compareTo(((IceCream)o2).date); 
    } 
} 
+0

如果它不難,那麼請告訴我 – user1091510

+0

@ user1091510請參閱我的編輯 – GETah

+0

我知道有人會用勺子喂答案!非常適合學習搜索技能。 – camickr

1

爲您的Icecream類定製比較器。

class DateComparator implements Comparator { 

    public int compare(Object ic1, Object ic22){ 

     /* 
     * parameter are of type Object, so we have to downcast it 
     * to Icecream objects 
     */ 

     Date ic1Date = ((Icecream)ic1).getDate();   
     Date ic2Date = ((Icecream)ic2).getDate(); 

     return ic1Date.compareTo(ic2Date); 
    } 
} 
1

我會做兩個類,一個實現比較器和一個處理數組排序的排序器,用比較器作爲參數。然後將冰淇淋放入一個陣列中,然後在分揀機中調用您的分揀方法。