Re: problem with TreeMap - element removal fails.



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

.



Relevant Pages

  • ASPX page jscript rt error: null is null or not an object
    ... A runtime error has occurred. ... So I click 'Yes' to debug and choose Microsoft Script Editor. ... var evt = this._getEvent; ... return function(source, args) { ...
    (microsoft.public.dotnet.framework.aspnet)
  • Word closes with Runtime error
    ... "Runtime Error! ... I can start Word from the RUN command using winword.exe /a, which starts Word without any addins, which would indicate that the error message is caused by an Addin problem. ... I REnamed the keys, placing OLD in front of each key and still have the same problem opening Word ...
    (microsoft.public.word.application.errors)
  • Re: Word closes with Runtime error
    ... "Runtime Error! ... I can start Word from the RUN command using winword.exe /a, which starts Word without any addins, which would indicate that the error message is caused by an Addin problem. ... I REnamed the keys, placing OLD in front of each key and still have the same problem opening Word ...
    (microsoft.public.word.application.errors)
  • Re: Tcl parsing
    ... The second one "may" raise a runtime error, ... proc f {args} { ...
    (comp.lang.tcl)