Reputation: 7553
I have a HashMap<String, ArrayList<String>>
. I am trying to convert it to a HashMap<String, String[]>
.
HashMap<String, ArrayList<String>> arrayListMap = new HashMap<>();
HashMap<String, String[]> arrayMap = new HashMap<>();
for (Map.Entry<String, ArrayList<String>> entry : arrayListMap.entrySet()) {
arrayMap.put(entry.getKey(), entry.getValue().toArray());
}
However, for entry.getValue().toArray()
, my IDE is giving me the error:
Wrong 2nd argument type. Found: 'java.lang.Object[], required 'java.lang.String[]'.
I don't know why, because the arrayListMap
specifies that I will be working with String
s.
Why is this not working, and how can I fix it?
Upvotes: 3
Views: 245
Reputation: 1046
HashMap<String, ArrayList<String>> arrayListMap = new HashMap<>();
HashMap<String, String[]> arrayMap = new HashMap<>();
for (Map.Entry<String, ArrayList<String>> entry : arrayListMap.entrySet()) {
arrayMap.put(entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()]));
}
entry.getValue().toArray() will return object array "object[]"
But need String[].
So need to use the method entry.getValue().toArray(T[] a) that returns T[] //generic arg type
Upvotes: -1
Reputation: 106390
ArrayList
has overloaded the toArray
method.
The first form, toArray()
, will return an Object[]
back. This isn't what you want, since you can't convert an Object[]
into a String[]
.
The second form, toArray(T[] a)
will return an array back that is typed with whatever array you pass into it.
You need to use the second form here so that the array is correctly typed.
arrayMap.put(entry.getKey(), entry.getValue()
.toArray(new String[entry.getValue().size()]));
Upvotes: 6