zaa*_*kun 6 java class list sorted arraylist
所以我现在正在为大学做一个有几个可选部分的练习(因为我们还没有在课堂上做过这个),其中一个是使用列表而不是数组(所以它是可变大小)而另一个是打印按点排序的列表(我现在就到了)
所以,我有一个看起来像这样的Player.java类.
public class Player {
String name;
String password;
int chips;
int points;
public Player (String n, String pw, int c, int p) {
name = n;
password = pw;
chips = c;
points = p;
}
public String getName () {
return name;
}
public void setName (String n) {
name = n;
}
public void setPW (String pw) {
password = pw;
}
public String getPW () {
return password;
}
public void setChips (int c) {
chips = c;
}
public int getChips () {
return chips;
}
public void setPoints (int p) {
points = p;
}
public int getPoints () {
return points;
}
Run Code Online (Sandbox Code Playgroud)
}
很简单,然后我用这个创建一个List(在另一个类中):
List<Player> lplayer = new ArrayList<Player>();
Run Code Online (Sandbox Code Playgroud)
添加玩家:
lplayer.add(new Player(n,pw,c,p))`
Run Code Online (Sandbox Code Playgroud)
最后用这个来阅读他们的统计数据:
public int search_Player (String n) {
String name;
int i = 0;
boolean found = false;
while ((i <= tp) && (!found)) {
name = lplayer.get(i).getName();
if (name.equals(n)) {
found = true;
}
i++;
}
return (found == true) ? i-1 : -1;
}
public Player show_Player (int i) {
return lplayer.get(i);
}
public void list_Players() {
Collections.sort(lplayer);
int i2;
if (tp > 0) { // variable which contains number of total players
for (int i = 0;i<tp;i++) {
i2 = i+1;
System.out.println ("\n"+i2+". "+lplayer.get(i).getName()+" [CHIPS: "+lplayer.get(i).getChips()+" - POINTS: "+lplayer.get(i).getPoints()+"]");
}
}
else {
System.out.println ("There are no players yet.");
}
}
Run Code Online (Sandbox Code Playgroud)
所以这基本上都是代码.正如您所看到的,我已经有了list_Players函数,但它只是按照添加的顺序打印出来.我需要一种打印方式,按每个玩家的积分排序(所以基本上是排名).
正如你所看到的,我对java很新,所以请尽量不要提出一个非常复杂的方法.
我已经搜索了它并发现了像Collections.sort(列表)这样的东西,但我想这不是我需要的东西.
谢谢!
您可以使用public static <T> void sort(List<T> list, Comparator<? super T> c)重载Collections- 提供您需要的比较器(可以只是一个匿名类) - 并且您已经完成了设置!
编辑: 这描述了该方法的工作原理.简而言之,您将实现您的通话
Collections.sort(list, new Comparator<Player>() {
int compare(Player left, Player right) {
return left.getPoints() - right.getPoints(); // The order depends on the direction of sorting.
}
});
Run Code Online (Sandbox Code Playgroud)
而已!