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 Strings.
Why is this not working, and how can I fix it?
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()]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With