简体   繁体   中英

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. I am not allowed to use a for loop of any sort. 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.

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.

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. You must change your 'Player' class to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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