List< String>到ArrayList< String>转换问题 [英] List<String> to ArrayList<String> conversion issue

查看:69
本文介绍了List< String>到ArrayList< String>转换问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法...实际上是获取句子列表并将每个句子拆分为单词.就是这样:

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?

此外,如果将HashMap中的ArrayList更改为List,我会得到

Also, if I change the ArrayList to List in a HashMap, I get

java.lang.UnsupportedOperationException

因为我的代码中有这行

sentenceList.add(((Element)sentenceNodeList.item(sentenceIndex)).getTextContent());

还有更好的建议吗?

推荐答案

首先,为什么地图是 HashMap< String,ArrayList< String>> 而不是 HashMap<; String,List< String>> ?出于某些原因,该值必须是接口 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+")));

这篇关于List&lt; String&gt;到ArrayList&lt; String&gt;转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆