Java: How can I implemement SortedMap i.e. TreeMap

35 Views Asked by At

I have implemented following classes:

public class Team - has a SortedMap<String, Player> as field. public class Player implements Comparator - has the method int compare(Object o1, Object o2)

Now, I want to have the Map always sorted when putting in String, Player.

How can I realize that, because the Comparator must work with the value Vand not with the key K. However, there is only a constructor with a Comparator of the key.

Thanks!

public class Player implements Comparator 

@Override
public int compare(Object o1, Object o2) {
    if(o1.getClass() != o2.getClass()) return 0;
    if(((int)((Player)o1).getName().charAt(0)) == ((int)((Player)o2).getName().charAt(0))) {
        if(((Player)o1).getNumber() == ((Player)o2).getNumber()) {
            return 0;
        } else if(((Player)o1).getNumber() < ((Player)o2).getNumber()) return -1;
        else return 1;
    } else if(((int)((Player)o1).getName().charAt(0)) < ((int)((Player)o2).getName().charAt(0))) {
        return -1;
    } else return 1;
}

The Team class:

public class Team {

    private SortedMap<String,Player> team;

    /**
     * This is the default constructor without parameters. It initializes the team Map
     */
    public Team() {
        team = new TreeMap(new Player(null, 0, 0));
    }

    /**
     * This method adds a new Player to the team-Map
     * @param player is the player to add to the team-Map
     */
    public void put(Player player) {
        if(player != null) {
           String name = player.getName();
           team.put(name, player);
        }
    }
0

There are 0 best solutions below