Community
Participate
Working Groups
I am using Version: 3.4.0, Build id: I20080330-1350 I have the following method: public void test(Map<Integer, String> map){ String key = null; map.get(key); } I was very surprised to see that I didn't get any errors or warnings. How can the String "key" be cast to an Integer without that being an error?
This is because, at least for the JDK 1.6 I use, Map<K, V>#get is defined as: V get(Object key); (and not as V get(K key), where K would resolve to Integer in your case). Hence no cast is needed at all. Please reopen if your definition of Map is different.
Thanks I had never noticed that. I had just assumed it would be "V get(K key)" without ever actually looking. They must have had some sort of implementation reason for doing it as get(Object), but I don't think it is very intuitive.
You're welcome. I believe this comes from upward compatibility needs indeed (the API used get(Object) in the past, hence there must be many calls out there that rely on this - note also that implementors may throw an exception if they are not happy with the type they get, but are not required to do so).
Yes, this is the idea. Same is true for list removals.
I did close this because I do agree that what is being done is "correct". But just like it is correct to have an unused private method (and you can generate a warning for that), it would be nice to have a warning (that could be turned on or off) for this case. I understand that the method signature needs to be this way for old code, but it is not what you would want or expect for new code. And over time you would want to fix up your old code as well.
The compiler does not define the libraries you compile against; it simply consumes them. Diagnosing what you wanted would mean that somewhere there would be a library of suggested replacement signatures to use, with proper diagnosis. I believe this is rather a job for a static analysis tool where it knows about code patterns etc...