5

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.

1
  • 1
    stackoverflow.com/questions/529085/… The thing is that it's not possible to create a generic array such as Entry<Character, Integer>[]. Use a List<Entry<Character, Integer>> instead. Commented May 19, 2013 at 10:41

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes it did.. great! Real magic.
1

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()));
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.