gpt4 book ai didi

java - 使用比较器将列表添加到树集中

转载 作者:行者123 更新时间:2023-12-01 17:53:24 25 4
gpt4 key购买 nike

因此,我必须创建一个分数高于给定分数的玩家对象的 TreeSet。我不允许使用任何类型的 for 循环。我已经编写了一个比较器并创建了所需对象的列表,但是当我将该列表添加到树集中时,我得到一个 Player 无法转换为 java.lang.Comparable 错误。

注意:一切正常,直到我尝试将其添加到树集中,如果我取出树集并只打印 highPlayers 它会给我我想要的列表。

为什么它不允许我将此列表添加到树集中?谢谢

public class TreeSetProblems2 {

public static void main(String[] args) {
List<Player> players = new ArrayList<>();

Player p1 = new Player("Tom", 3);
Player p2 = new Player("Bucky", 42);
Player p3 = new Player("Tina", 23);
Player p4 = new Player("Bob", 15);
Player p5 = new Player("Shaun", 2);
//Player p6 = new Player("Tommy", 3);

players.add(p1);
players.add(p2);
players.add(p3);
players.add(p4);
players.add(p5);

System.out.print(highRollers(players, 9));
}

public static TreeSet<Player> highRollers(List<Player> players, int score){
TreeSet<Player> treeplayers = new TreeSet<>();
Player dummy = new Player("Dummy", score);
players.add(dummy);
ScoreComparator sc = new ScoreComparator();
Collections.sort(players, sc);
int index = players.indexOf(dummy);
List<Player> highPlayers = players.subList(index+1, players.size());
treeplayers.addAll(highPlayers);
return treeplayers;
}


}

最佳答案

我发现了自己的解决方案:

public static TreeSet<Player> highRollers(List<Player> players, int score) {
TreeSet<Player> treeplayers = new TreeSet<>(new ScoreComparator());
treeplayers.addAll(players);

while(treeplayers.first().getScore() < score) {
treeplayers.pollFirst();
}

return treeplayers;
}

或者更简单:

public static TreeSet<Player> highRollers(List<Player> players, int score) {
TreeSet<Player> treeplayers = new TreeSet<>(new ScoreComparator());
TreeSet<Player> highRollers = new TreeSet<>(new ScoreComparator());

treeplayers.addAll(players);
highRollers.addAll(treeplayers.tailSet(new Player("Dummy", score)));

return highRollers;
}

关于java - 使用比较器将列表添加到树集中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47564993/

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