我有一个包含两个属性的类:
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类包含palyer对象的集合。
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 :(得分:3)
使用anonymous inner class,Comparator和Collections.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());
}
});.
答案 1 :(得分:1)
撰写Comparator并使用它按点List
排序。您只是比较Player
个实例。
答案 2 :(得分:1)
是的,用player
课程实施Comparable(请使用“播放器”,课程大写第一个字母,否则会让人感到困惑):
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;
}
}
然后,您可以使用List
Collections.sort(players);
进行排序
答案 3 :(得分:1)
所以你想知道那些得分差异最小的球员? 虽然Apache Commons Collections中可能存在某些内容,但我认为没有API功能。
否则你将不得不使用嵌套循环。
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( ));
显然,这段代码需要一些工作;例如,如果两对玩家之间具有相同的差异,则仅报告处理的最新对。您可能还想重新处理这段代码以删除默认值(例如,如果您的List包含0个玩家,请注意System.out.println
将如何崩溃)。我留下这些给你解决。 HTH。