2012-02-26 120 views
1

我是一名C++程序員,現在我正在使用Java(我確實擁有大量的Java經驗)。在Java中自定義排序的最佳方式是什麼?

基本上,我想重新創建我在C++中經常使用的pair<int,int>,並且我想讓它按第二個整數值排序。

我在互聯網上搜索,並嘗試的要對此,使用比較包括不同的方式,可比等

我基本上是創建一個測試程序,它看起來像這樣:

import java.math.*; 
import java.util.*; 
import java.io.*; 
import java.text.*; 

class PairTest 
{ 

    public static void main (String args[]) // entry point from OS 
    { 
     new PairTest().run(); 


    } 

    public void run(){ 
     Pair foo = new Pair(1,2); 
     System.out.println(foo.first + " "+ foo.second); 
     ArrayList <Pair> al = new ArrayList<Pair>(); 
     for(int i =10;i>0;i--){ 
      al.add(new Pair(i, i*2)); 
     } 
     for(int i =0;i<al.size();i++){ 
      System.out.println(al.get(i).first + " " + al.get(i).second); 
     } 
     Collections.sort(al); 
     for(int i =0;i<al.size();i++){ 
      System.out.println(al.get(i).first + " " + al.get(i).second); 
     } 
    } 

    private class Pair implements Comparable{ 

     public int first; 
     public int second; 

     public Pair (int a, int b){ 
      this.first = a; 
      this.second = b; 

     } 

     int compareTo (Pair o){ 
      return new Integer(this.second).compareTo(new Integer(o.second)); 
     } 
    } 

} 

什麼是最好的方式去做一個自定義的排序函數,以便ArrayList按「第二個」變量排序。我想要一個快速而安全的方法,目前,編譯器告訴我「PairTest.Pair不會覆蓋抽象方法compareTo ...」

我真的不知道發生了什麼,任何幫助將不勝感激。

+0

是的,我想,用適當的鑄造,但我的程序給我打電話Collections.sort麻煩時(); – 2012-02-26 03:30:39

+0

而不是一個列表中的排序對,一個常見的模式是使用一個地圖,只要這些值是唯一的(即使沒有,也有解決方案),例如嘗試'TreeMap '你正在排序的值是關鍵。 – 2012-02-26 07:55:46

回答

5

您的Pair類有兩個問題:它沒有聲明通用參數,而compareTo方法需要爲public。此外,返回int值之間的差異比構造Integer對象和調用compareTo更有效。試試這個:

private class Pair implements Comparable<Pair> { 

    public int first; 
    public int second; 

    public Pair (int a, int b){ 
     this.first = a; 
     this.second = b; 

    } 

    public int compareTo (Pair o){ 
     return second < o.second ? -1 : (second == o.second ? 0 : 1); 
    } 
} 
+0

不錯,那就是訣竅! (看起來Comparable 是造成大部分問題的原因) – 2012-02-26 03:31:07

+1

不是再次破解..給定的compareTo版本是正確的,但這不是。例如2 ** 30當然大於-2 ** 30。我的一位教授曾經說過,「如果它不一定是正確的,我可以任意快速地使它......」 – Voo 2012-02-26 03:43:54

+0

@Voo - 好點。我更新了代碼以避免溢出問題;現在在所有情況下都應該是正確的。儘管原始的compareTo是正確的,但效率非常低下 - 每次比較都需要兩個Integer對象。 – 2012-02-26 06:31:15

2

在你的代碼,你應該改變:

private class Pair implements Comparable 

private class Pair implements Comparable<Pair> 

你改變這一行:

int compareTo (Pair o) 

public int compareTo (Pair o) 

,因爲這個功能將是這個類的境外使用:)

這就是你需要:)

+0

+1簡潔而簡潔,但有人已經通過給我一個關於程序應該如何的樣子的例子來打敗你:) – 2012-02-26 03:32:36

1

覆蓋comapreToPair類方法。無需執行任何操作。

comapreTo方法接受Object作爲參數

public int compareTo(Object another) 
{ 
    return new Integer(this.second).compareTo(new Integer(((Pair)another).second)); 
} 
相關問題