比较

2011-08-30 81 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