Re: Generics on map.
Putting the response before the stimulus.
What is "top-posting?"
Please don't top-post.
Ravi wrote:
Its quite obvious that runtime return value from the get() is null.
But the very idea of generics is to avoid these runtime mistakes(??)
and push them to design (compile) time. Wont it make sense to throw up
at least a warning that the key is of incompatible type ?? btw, put()
does care about the type check for Key and Value .
Of course put() is parameterized, because it needs to ensure
that you don't insert a String key into a Map that expects only
Integers. But get() doesn't need to be so picky: If you search
that Map for an entry with the key "Mongo", get() reports that
no such entry exists. Nothing odd about that, is there?
Consider this pre-generics situation: I've got a Map
Map squares = new HashMap();
.... and I populate it with some data
for (int n = 0; n < 10; ++n)
squares.put(new Integer(n), new Integer(n*n));
Now I make some queries:
Integer value1 = (Integer)squares.get(new Integer(5));
Integer value2 = (Integer)squares.get(new Integer(42));
Integer value3 = (Integer)squares.get("Mongo");
The first query returns a reference to an Integer with the
value 25. The second returns null because the Map has no
entry with the key 42. And the third returns null because
the Map has no entry with the key "Mongo". What difference
is there between the second and third outcomes? None; they
both declare "key not found," and there's an end on't.
Remember, too, that generics are a compile-time hint and
not a run-time enforcement. By ignoring enough warnings you
can in fact put a String key and a BigDecimal value into a
Map<Integer,Integer> -- and if you were to do so, and then
turn around and search for the String key, shouldn't get()
find the BigDecimal for you?
I imagine that the design decisions might have been made
differently if generics had been part of Java from the start
and if they were backed up by run-time enforcement. But for
whatever reason that's not the way things have turned out.
--
Eric.Sosman@sun.com