Java 如何将字符串[]转换为集合?

Java 如何将字符串[]转换为集合?,java,arrays,string,collections,set,Java,Arrays,String,Collections,Set,我这样做: Set<String> mySet = new TreeSet<String>(); String list = ("word,another,word2"); // actually this is much bigger String[] wordArr = list.split(","); mySet.addAll(wordArr); Set mySet=new TreeSet(); 字符串列表=(“单词,另一个,单词2”);//实际上,这个要大得多

我这样做:

Set<String> mySet = new TreeSet<String>();
String list = ("word,another,word2"); // actually this is much bigger
String[] wordArr = list.split(",");
mySet.addAll(wordArr);
Set mySet=new TreeSet();
字符串列表=(“单词,另一个,单词2”);//实际上,这个要大得多
字符串[]wordArr=list.split(“,”);
mySet.addAll(wordArr);
这会产生以下错误:

 The method addAll(Collection<? extends String>) in the type Set<String> is
 not applicable for the arguments (String[])

方法addAll(Collection方法
树集
构造函数接受一个
集合
,一个
字符串[]
可以转换成一个
列表
,它使用
数组实现
集合

publicstaticvoidmain(字符串[]args){
String list=“word,other,word2”;//此处不需要()
字符串[]wordArr=list.split(“,”);
Set mySet=newtreeset(Arrays.asList(wordArr));
for(字符串s:mySet){
系统输出打印项次;
}
}
下面是一个使用以下内容的示例:


查看
Arrays.asList
@SotiriosDelimanolis A-1?拜托,伙计,你本可以给出你的评论作为答案!!至少这会有帮助。我没有投反对票,但在这里和网络上有很多其他资源可以给你答案。@BlueFlame注意,这个问题已经被问过并回答过了(标题几乎完全相同)。下一票按钮上的工具提示显示“此问题不显示任何研究成果”。人们可能会下一票,因为搜索问题的标题会为您找到答案。@BlueFlame是的,在询问有关堆栈溢出的问题之前,堆栈溢出是您应该搜索的地方之一。:)不需要google.commons。我的教授可能不允许这样做。@BrianRoach如果我真的想写这段代码,我想我不会添加它。但是对于一个足够大的项目,我的类路径中可能已经有了它。为什么要使用一个巨大的第三方依赖项来做:
newtreeset(Array.asList(wordArr));
(无意中删除了此项而不是编辑)您甚至不需要
addAll
。集合构造函数将接受集合,因此您可以使用
set mySet=new TreeSet(Arrays.asList(wordArr));
@JoshuaTaylor谢谢你的建议。我已经更新了答案。不过,不仅仅是
TreeSet
有这样的构造函数。集合通常有接受集合的构造函数。例如,在的文档中,有一条注释,“程序员通常应该提供一个void(无参数)和集合构造函数,按照集合接口规范中的建议。”@JoshuaTaylor,这很好知道。因此总结一下,您可以实例化大多数(或任何?)通过向构造函数提供
Collection
来收集?您不能保证实现收集的类有这样的构造函数,但标准库中提供的所有标准类都有这样的构造函数。接口的javadoc确实说明:
public static void main(String[] args) {

    String list = "word,another,word2"; //No need for () here
    String[] wordArr = list.split(",");
    Set<String> mySet = new TreeSet<String>(Arrays.asList(wordArr));

    for(String s:mySet){
        System.out.println(s);
    }

}
package com.sandbox;


import com.google.common.collect.Sets;

import java.util.Set;

public class Sandbox {

    public static void main(String[] args) {
        String list = ("word,another,word2"); // actually this is much bigger
        String[] wordArr = list.split(",");
        Set<String> mySet = Sets.newHashSet(wordArr);
    }        
}
package com.sandbox;


import java.util.Set;
import java.util.TreeSet;

public class Sandbox {

    public static void main(String[] args) {
        Set<String> mySet = new TreeSet<String>();
        String list = ("word,another,word2"); // actually this is much bigger
        String[] wordArr = list.split(",");
        for (String s : wordArr) {
            mySet.add(s);
        }
    }


}