Re: problem with TreeMap - element removal fails.
- From: "Chris Uppal" <chris.uppal@xxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Mon, 17 Jul 2006 10:59:03 +0100
tomek milewski wrote:
import java.util.TreeMap;
class A {
public A() {
}
public static final void main(String[] args) {
A a = new A();
TreeMap<A, Integer> map = new TreeMap<A, Integer>();
map.put(a, new Integer(1));
map.remove(a);
}
}
Executing last line of this code throws ClassCastException. Why element
can be putted into this TreeMap and can't be removed?
It's because your class A does not implement the Comparable interface. If you
don't provide an explicit Comparator (as the parameter to the TreeMap's
constructor) then the TreeMap will attempt to use its keys' "natural ordering",
as defined by their own compareTo() methods. Since you don't provide that
method (and don't implement the corresponding interface), it fails at runtime.
Arguably it should fail when the first entry is added, rather than when it
first needs to compare two entries -- that would have been less confusing in
this case. (Also a ClassCastException would be more use if its toString()
mentioned what the failed target class/interface was.)
The new Java generics type system is not powerful enough to express the fact
that the key type must implement Comparable /unless/ an explicit comparator is
provided[*], which is why the compiler doesn't prevent you from making this
mistake.
-- chris
([*] At least, I don't think it's powerful enough. Maybe some horror of
twisted generic declarations could be concocted which had that effect -- if it
is possible then we're fortunate that Sun didn't inflict it on us ;-)
.
- References:
- problem with TreeMap - element removal fails.
- From: tomek milewski
- problem with TreeMap - element removal fails.
- Prev by Date: Re: Byte Array
- Next by Date: Re: What is SOA?
- Previous by thread: Re: problem with TreeMap - element removal fails.
- Next by thread: Good practise?
- Index(es):