我这样做了:
Set<String> mySet = new TreeSet<String>();
String list = ("word,another,word2"); // actually this is much bigger
String[] wordArr = list.split(",");
mySet.addAll(wordArr);
这会出错:
The method addAll(Collection<? extends String>) in the type Set<String> is
not applicable for the arguments (String[])
我认为我的意图很清楚。
问题:是否有更好的方法来实现我想要的设置?我知道我的名单中没有重复的值。
答案 0 :(得分:4)
TreeSet
构造函数接受Collection
,String[]
可以转换为使用List
实现Collection
的{{1}}。
Arrays.asList()
答案 1 :(得分:1)
以下是使用Guava的示例:
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);
}
}
如果你想在没有Arrays
的情况下这样做(我不推荐,但你在课堂上,所以也许你不能使用它):
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);
}
}
}