列表<字符串>到 ArrayList<String>转换问题 [英] 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>>
所以这个方法返回List,我需要一个arrayList?如果我尝试投射它不会锻炼...有什么建议吗?
so this method returns List and I need a arrayList? If I try to cast it doesn't workout... any suggestions?
此外,如果我将 ArrayList 更改为 HashMap 中的 List,我会得到 p>
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());
有什么更好的建议吗?
推荐答案
首先,为什么映射是 HashMap
而不是 HashMap<;字符串,列表<字符串>>
?为什么值必须是接口List
(在本例中为ArrayList
)的特定实现?
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
不返回 java.util.ArrayList
,因此您不能分配 Arrays.asList
的返回值到 ArrayList
类型的变量.
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
.
代替:
allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));
试试这个:
allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));
这篇关于列表<字符串>到 ArrayList<String>转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!