Skip to content
Advertisement

List to ArrayList conversion issue

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 a following format

HashMap<String, ArrayList<String>>

so this method returns List and I need a arrayList? If I try to cast it doesn’t workout… 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?

Advertisement

Answer

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+")));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement