比較

2011-08-30 82 views
2

我有一個包含兩個屬性的類:比較

public class player{ 
    public player(String playerName,int points){ 
     this.playerName=playerName; 
     this.points=points; 
    } 
    public String getPlayerName() { 
     return playerName; 
    } 
    public void setPlayerName(String playerName) { 
     this.playerName = playerName; 
    } 
    public int getPoints() { 
     return points; 
    } 
    public void setPoints(int points) { 
     this.points = points; 
    } 
    private String playerName; 
    private int points; 
} 

我有ArrayList類包含在線播放對象的集合。

List palyers=new ArrayList(); 
players.add(new player("mike",2)); 
players.add(new player("steve",3)); 
players.add(new player("jhon",7)); 
players.add(new player("harry",5); 

這裏我的問題是如何顯示具有最小分差的玩家名稱。

輸出:

Based on the example code i written: 

Mike and steve is the output 

THis way comparison should happen: 

mike to steve --> 1 

mike to jhon--->5 

mike to harry-->3 

steve to mike -->1 
steve to jhon--->5 
steve to harry--->3 

jhon to mike-->5 
jhon to steve-->4 
jhon to harry--->2 

harry to mike -->3 

harry to steve-->2 

harry to jhon -->2 

Based on above comparison mike and steve should display 

任何Java API的性能比較?

+0

嗨,謝謝你的回答,但是在這裏我不需要按照排序順序排列積分。我希望最終的結果能夠顯示出積分最小的玩家。 – Raj

回答

1

所以你想知道比分差距最小的那對球員嗎? 我不認爲有這樣的API函數,雖然Apache Commons Collections中可能有些東西。

否則,你將不得不使用嵌套循環。

int res1 = -1, res2 = -1; 

int maxDiff = Integer.MAX_VALUE; 
for (int i = 0; i < players.size(); i++) 
{ 
    for (int j = i + 1; j < players.size() ; j++) 
    { 
     int diff = Math.abs(players.get(i).getPoints() - players.get(j).getPoints()); 
     if (diff < maxDiff) 
     { 
      maxDiff = diff; 
      res1 = i; 
      res2 = j; 
     }   
    } 
} 
System.out.println(players.get(res1).getPlayerName() + " and " + players.get(res2).getPlayerName()); 

顯然,這個代碼需要一些工作;例如,如果兩對玩家之間的差異相同,則只報告最近處理的一對玩家。您可能還想重新編寫這段代碼以刪除默認值(請注意,如果列表包含0個播放器,System.out.println將如何崩潰)。我留下這些給你解決。 HTH。

1

編寫Comparator並用它按點排序List。你只是比較Player實例。

+0

嗨,謝謝你的回答,但是這裏我不需要排序的points.I想要最終的結果顯示在他們的點差異最小的球員 – Raj

+0

@Raju Komaturi你可以自定義比較排序點差異,而不是隻是點。 –

+0

邁克和史蒂夫是輸出 – Raj

1

是,實施Comparableplayer類(請用 「播放器」,爲類首字母大寫,否則就混淆):

public class Player implements Comparable<Player> 
{ 


.... 


    public int compareTo(Player other) 
    { 
     if (this.points == other.points) 
      return 0; 
     if (this.points > other.points) 
      return 1; 
     return -1; 
    } 

} 

然後你就可以使用Collections.sort(players);

+0

之間的點差異嗨,感謝您的所有答案,但在這裏我不需要排序順序points.I要最終結果顯示在他們的點差異最小的球員 – Raj

3

使用排序Listanonymous inner class,ComparatorCollections.sort()

Collections.sort(palyers, new Comparator(){ 
     public int compare(Object o1, Object o2){ 
      player p1 = (player) o1; 
      player p2 = (player) o2; 

      return p1.getPoints().compareTo(p2.getPoints()); 
      } 
     });. 
+0

+1 :我更喜歡你在課堂上進行比較的方法,因爲這比較靈活。 – alpian

+0

嗨,感謝您的答案,但在這裏我不需要排序順序點。我想要一個最終結果來顯示他們的積分差異最小的球員 – Raj

+0

@Zengr:我編輯了我的問題,請找到輸出部分。 – Raj