문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

I am not sure exactly on the ways you tried. What I would do is

When you do that you'll get an EntrySet, so the data will be stored as Entry

So if you want to keep it in the EntrySet you can do this:

List<Entry<Character, Integer>> list = new ArrayList<Entry<Character, Integer>>();

for(Entry<Character, Integer> entry : map.entrySet()) {
    list.add(entry);
}

Also note that you will always get a different order when doing this, as HashMap isn't ordered.

Or you can do a class to hold the Entry data:

public class Data {
    public Character character;
    public Integer value;

    public Data(Character char, Integer value) {
       this.character = character;
       this.value = value;
    }
}

And extract it using:

List<Data> list = new ArrayList<Data>();

for(Entry<Character, Integer> entry : map.entrySet()) {
    list.add(new Data(entry.getKey(), entry.getValue()));
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top