gpt4 book ai didi

java - Pojo类属性比较

转载 作者:行者123 更新时间:2023-11-30 05:56:23 25 4
gpt4 key购买 nike

我有一个包含两个属性的类:

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来比较属性?

最佳答案

使用anonymous 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());
}
});.

关于java - Pojo类属性比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7249919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com