2011-04-21 29 views
0

我試圖理清一個ArrayList,但我不能換我的頭周圍比較。我不明白如何定義從文本文件創建的我的數組列表中的可排序字段。此外,我不確定比較器邏輯。在我看來,像創建一組比較函數,然後調用它們。這是真的?我想不通比較

到目前爲止,我的代碼如下所示:

public class coord implements Comparator<Sort> { 
    private int index; 
    private int index2; 
    private double dista; 
} 

public class Sort { 
List<Sort> coords = new ArrayList<Sort>(); 


public static void main(String[] args) throws Exception { 
    ArrayList dist = new ArrayList(); 
    File file = new File("2.txt"); 
    FileWriter writer = new FileWriter("2c.txt"); 
    try { 
     Scanner scanner = new Scanner(file).useDelimiter("\\s+"); 

     while (scanner.hasNextLine()) 
     { 
      int index = scanner.nextInt(); 
      int index2 = scanner.nextInt(); 
      double dista = scanner.nextDouble(); 
      System.out.println(index + " " + index2 + " " + dista); 
     } 
    } 
} 
     public class EmpSort { 
      static final Comparator<coord> SENIORITY_ORDER = 
             new Comparator<coord>() { 
       public int compare(coord e1, coord e2) { 
        return e2.index().compareTo(e1.index()); 
       } 
      }; 
      static final Collection<coord> coords = ; 

      public static void main(String[] args) { 
       List<Sorted>e = new ArrayList<Sorted>(coords); 
       Collections.sort(e, SENIORITY_ORDER); 
       System.out.println(e); 

我感謝所有幫助任何人都可以給。

+1

此代碼是不完整的。嘗試沒有catch或finally子句。 – Srikanth 2011-04-21 20:27:48

+0

我認爲你有一堆模板。使用鉛筆和紙張繪製您的對象系統,顯示層次結構和關係。這將需要10分鐘的時間,並清除你的想法。 – slezica 2011-04-21 20:29:05

回答

1

比較邏輯是簡單的。當對一組元素進行排序時,您有兩個選擇 - 使用每個元素上的Comparable(假設有一個)進行排序,或者提供一個比較器。如果你的數組包含複雜的元素或有不同的排序標準,那麼後一種選擇可能是你需要使用的。

每次所述比較器被稱爲必須說,如果元件1是「小於」元件2在這種情況下返回一個負數,元件1是元件3「大於」在這種情況下返回一個正數。否則,如果元素相等,則返回0.您也可以在比較值之前進行引用和空比較,以便null元素在邏輯上「小於」非空元素等等。

如果元素是「平等」,那麼你可能希望通過二次字段進行排序,然後第三場和繼續下去,直到排序順序是明確的。

一類複雜的它有一個簡單的比較字段一個& B和我們要排序上:

class Complex { 
    public String a = ""; 
    public String b = ""; 
} 

//... 

Collections.sort(someList, new Comparator<Complex>() { 
    public int compare(Complex e1, Complex e2) { 
    if (e1 == e2) { 
     // Refs could be null or equal 
     return 0; 
    } 
    if (e1 == null && e2 != null) { 
     return -1; 
    } 
    if (e2 == null && e1 != null) { 
     return 1; 
    } 
    if (e1.a == e2.a) { 
     return 0; 
    } 
    if (e1.a == null && e2.a != null) { 
     return -1; 
    } 
    if (e1.a != null && e2.a == null) { 
     return 1; 
    } 
    // Just use the Comparable on the fields 
    return e1.a.compareTo(e2.a); 
    } 
});