Re: problem with TreeMap - element removal fails.



Ingo R. Homann wrote:

Well, to make the TreeMap work correctly, it is necessary that the keys implement Comparable. So it is obvious that your code cannot work.

Keys of TreeMap don't have to implement Comparable when you provide a keys Comparator to the map's constructor.

That is true reason of why:

TreeMap is defined as "TreeMap<K,V>" and not as "TreeMap<K extends Comparable,V>".


Having said this (and thinking more about it), I think it would be good if the runtime error would be thrown in the constructor (fail early)!

Impossible. TreeMap constructors have no knowledge on its generic parameters types neither its future elements types.


piotr
.



Relevant Pages

  • Re: Help with sorting values in a TreeMap
    ... > the map is an AccountView object whose 'getKey' method returns the ... > I use TreeMap so that they sort nicely by the account number. ... When you construct a TreeMap with a Comparator, ... The objects that it would be comparing _are_ the keys that you described, ...
    (comp.lang.java.programmer)
  • Re: problem with TreeMap - element removal fails.
    ... Keys of TreeMap don't have to implement Comparable when you provide a keys Comparator to the map's constructor. ...
    (comp.lang.java.programmer)
  • Re: Comparator
    ... You say you have implemented the java.util.Comparator interface ... java.util.TreeMapconstructor, ... there is no "original" Comparator. ... meaning that the keys must implement the java.lang.Comparable interface ...
    (comp.lang.java.programmer)
  • Re: TreeMap and Comparator question
    ... Comparator to a TreeMap, it must comparekeys, you can't compare ... What I've done before, when I needed a map sorted by values, was to ... But I would like to be able to sort by keys or values when I wanted, ... Jakarta Commons Collectionshas a SortedBidiMap, ...
    (comp.lang.java.programmer)
  • Re: Sort Map on Value
    ... Since the name can repeat I cannot use it ... but isn't the TreeMap designed to be ... able to use a custom Ordering? ... Create a Comparator like Eric did ...
    (comp.lang.java.programmer)