TreeMap error

Discussion in 'Plugin Development' started by Herobrinedobem, Aug 5, 2014.

Thread Status:
Not open for further replies.
  1. Offline


    Hello, I have a problem in my code, I have a TreeMap (First time I'm using a map of this kind) see:

    private static TreeMap<Player, Integer> apostas = new TreeMap<Player, Integer>();

    When the player enters /command <money> the error in this line:

    Variaveis.getApostas().put(p.getPlayer(), aposta_player_int);
  2. Offline


    IDE/Compile error?
    can you post the full code block with variables and such?
    it will just help wiyh finding the problem
  3. Offline



    Error: Caused by: java.lang.ClassCastException: org.bukkit.craftbukkit.v1_5_R3.entity.C
    raftPlayer cannot be cast to java.lang.Comparable

    Soon I will post the code, one minute
  4. Offline


    When you put keys in a tree map, they must implement Comparable.

    So your keys must pass through a Comparator of some kind.


    Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.
  5. Offline


    Herobrinedobem why would you make a TreeMap with Player keys? (Since TreeMaps sort by key)
  6. Offline


    Exactly - that's two reasons not to use a Player object as a key:
    • Memory leaks (which applies to other Map implementations too)
    • Player (CraftPlayer) doesn't implement Comparable, making it useless as a TreeMap key.
    Use the player's name or (preferably) UUID as the key, and you should be fine.
  7. Offline


    desht likes this.
Thread Status:
Not open for further replies.

Share This Page