Re: problem with TreeMap - element removal fails.
- From: "Ingo R. Homann" <ihomann_spam@xxxxxx>
- Date: Mon, 17 Jul 2006 11:11:39 +0200
Hi,
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.
Well, to make the TreeMap work correctly, it is necessary that the keys implement Comparable. So it is obvious that your code cannot work.
Having said this, I must admit that at first I was a bit suprised that TreeMap is defined as "TreeMap<K,V>" and not as "TreeMap<K extends Comparable,V>". Then, you would get a compiler error instead of a runtime error, which would be better. But I guess this is a generics-problem: For a Map, it is generally not necessary that the key implements Comparable (e.g. for a HashMap it is not necessary). So, because a TreeMap should be assignable to a Map, it cannot be defined different.
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)!
Ciao,
Ingo
.
- Follow-Ups:
- Re: problem with TreeMap - element removal fails.
- From: Piotr Kobzda
- Re: problem with TreeMap - element removal fails.
- References:
- problem with TreeMap - element removal fails.
- From: tomek milewski
- problem with TreeMap - element removal fails.
- Prev by Date: Re: jdk 5 generic, why not the other way arround for (T[] e, Collection<T> c)
- Next by Date: Re: The Right Level of Patterns
- Previous by thread: problem with TreeMap - element removal fails.
- Next by thread: Re: problem with TreeMap - element removal fails.
- Index(es):
Relevant Pages
|