List<String> to ArrayList<String> conversion issue

arraylist, java, list

Solution

First of all, why is the map a `HashMap<String, ArrayList<String>>` and not a `HashMap<String, List<String>>`? Is there some reason why the value must be a specific implementation of interface `List` (`ArrayList` in this case)?

`Arrays.asList` does not return a `java.util.ArrayList`, so you can't assign the return value of `Arrays.asList` to a variable of type `ArrayList`.

Instead of:

allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));

Try this:

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

Problem

I have a following method...which actually takes the list of sentences and splits each sentence into words. Here is it: ``` public List<String> getWords(List<String> strSentences){ allWords = new ArrayList<String>(); Iterator<String> itrTemp = strSentences.iterator(); while(itrTemp.hasNext()){ String strTemp = itrTemp.next(); allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+")); } return allWords; } ``` I have to pass this list into a hashmap in the following format ``` HashMap<String, ArrayList<String>> ``` so this method returns List and I need an ArrayList? If I try to cast it doesn't work out... any suggestions? Also, if I change the ArrayList to List in a HashMap, I get ``` java.lang.UnsupportedOperationException ``` because of this line in my code ``` sentenceList.add(((Element)sentenceNodeList.item(sentenceIndex)).getTextContent()); ``` Any better suggestions?

Original source