简体   繁体   English

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

[英]Adding a list to a tree set using a comparator

So, I have to create a TreeSet of player objects that have a score higher then a given score. 因此,我必须创建一个分数高于给定分数的播放器对象的TreeSet。 I am not allowed to use a for loop of any sort. 我不允许使用任何形式的for循环。 I have wrote a comparator and have created a list of the need object but when I add the list to the treeset I get a Player cannot be cast to java.lang.Comparable error. 我已经编写了一个比较器并创建了Need对象的列表,但是当我将列表添加到树集时,我得到一个Player不能转换为java.lang.Comparable错误。

Note: Everything works untill I try to add it to the treeset, if I take the treeset out and just print highPlayers it give me the list I want. 注意:一切正常,直到我尝试将其添加到树集中,如果我将树集取出并只打印highPlayers,它就会给我我想要的列表。

Why is it not letting me add this list to the treeset? 为什么不让我将此列表添加到树集? Thanks 谢谢

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;
    }


} 

I have discover my own solution: 我发现了自己的解决方案:

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;
}

Or even simpler: 甚至更简单:

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;
}

The key point appears to be that a TreeSet can only contain elements of a class which implement the Comparable interface. 关键点似乎是TreeSet只能包含实现Comparable接口的类的元素。 You must change your 'Player' class to do so. 您必须更改“ Player”类才能这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM