Why 2 castings in return statement of entrySet() of HashMap?
Hi
When looking through the code of the HashMap class in jdk 1.5 in Eclipse 3.2 I see the following:
public Set<Map.Entry><K,V>> entrySet() {
Set<Map.Entry><K,V>> es = entrySet;
return (es != null ? es : (entrySet = (Set<Map.Entry><K,V>>) (Set) new EntrySet()));
}
Here I am wondering why there in the return statement are 2 (two) castings:
return (es != null ? es : (entrySet = (Set<Map.Entry><K,V>>) (Set) new EntrySet()));
, where I think of (Set<Map.Entry><K,V>>) (Set)
Can anyone give me a good explanation to this?
Thank you!
[673 byte] By [
3numa] at [2007-10-3 5:20:40]

Hi,
you're right: the casts are not really necessary at all, since an assignment from a raw type is possible without an explicit cast. Either with or without the casts, the compiler will issue an "unchecked" warning.
(And, of course, a single cast to the target type would also work here.)
The "correct" way to fix the code would be to make the inner class EntrySet a parameterized class by deriving it from AbstractSet<Map.Entry><K,V>>. Then all "unchecked" warnings would automatically disappear.
My guess is that by the time the developer generified the HashMap, there where still compiler bugs preventing him from declaring inner classes such as EntrySet correctly. Since then, nobody's touched the code again.