Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<String> to ArrayList<String> 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?

like image 775
Skipper07 Avatar asked Oct 30 '12 08:10

Skipper07


People also ask

Can we convert list to ArrayList?

Convert list To ArrayList In Java. ArrayList implements the List interface. If you want to convert a List to its implementation like ArrayList, then you can do so using the addAll method of the List interface.

Can we convert string to ArrayList?

We can easily convert String to ArrayList in Java using the split() method and regular expression.

How will you convert a string array to an ArrayList?

To convert string to ArrayList, we are using asList() , split() and add() methods. The asList() method belongs to the Arrays class and returns a list from an array. The split() method belongs to the String class and returns an array based on the specified split delimiter.

How do I convert a string to an ArrayList in Java?

1) First split the string using String split() method and assign the substrings into an array of strings. We can split the string based on any character, expression etc. 2) Create an ArrayList and copy the element of string array to newly created ArrayList using Arrays. asList() method.


1 Answers

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); 
like image 112
SJuan76 Avatar answered Sep 22 '22 22:09

SJuan76