List<String> to ArrayList<String> conversion issue

Skipper07 picture Skipper07 · Oct 30, 2012 · Viewed 217.2k times · Source

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?

Answer

SJuan76 picture SJuan76 · Oct 30, 2012

Cast works where the actual instance of the list is an ArrayList. If it is, say, a Vector (which is another extension of List) it will throw a ClassCastException.

The error when changing the definition of your HashMap is due to the elements later being processed, and that process expects a method that is defined only in ArrayList. The exception tells you that it did not found the method it was looking for.

Create a new ArrayList with the contents of the old one.

new ArrayList<String>(myList);