How to convert hashmap to Array of entries

Yoda picture Yoda · May 19, 2013 · Viewed 9.9k times · Source

I have a map

private HashMap<Character, Integer> map;

I want to convert it to array but when I do that/I get this:

Entry<Character, Integer> t = map.entrySet().toArray();    
**Type mismatch: cannot convert from Object[] to Map.Entry<Character,Integer>**

Entry<Character, Integer>[] t = null;
map.entrySet().toArray(t); 
**Exception in thread "main" java.lang.NullPointerException**

Entry<Character, Integer>[] t = new Entry<Character, Integer>[1];
map.entrySet().toArray(t); 
   **Cannot create a generic array of Map.Entry<Character,Integer>**

Entry<Character, Integer>[] t = null;
t = map.entrySet().toArray(t); 
**Exception in thread "main" java.lang.NullPointerException**

So how to convert HashMap to Array? None of answers found in other subjects work.

Answer

Stephen C picture Stephen C · May 19, 2013

I think this will work:

Entry<Character, Integer>[] t = (Entry<Character, Integer>[])
        (map.entrySet().toArray(new Map.Entry[map.size()]));    

... but you need an @SuppressWarning annotation to suppress the warning about the unsafe typecast.