我需要创建一个具有初始值的集合。
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。
我需要创建一个具有初始值的集合。
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。
当前回答
随着java9和方便的工厂方法的发布,这可以以一种更干净的方式实现:
Set set = Set.of("a", "b", "c");
其他回答
我觉得最有可读性的是简单地使用谷歌番石榴:
Set<String> StringSet = Sets.newHashSet("a", "b", "c");
这是可变的。
如果你只有一个值,想要得到一个不可变的集合,这就足够了:
Set<String> immutableSet = Collections.singleton("a");
结合Michael Berdyshev的回答和泛型,并使用initialCapacity构造函数,与数组进行比较。asList变体:
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@SafeVarargs
public static <T> Set<T> buildSetModif(final T... values) {
final Set<T> modifiableSet = new HashSet<T>(values.length);
Collections.addAll(modifiableSet, values);
return modifiableSet;
}
@SafeVarargs
public static <T> Set<T> buildSetModifTypeSafe(final T... values) {
return new HashSet<T>(Arrays.asList(values));
}
@SafeVarargs
public static <T> Set<T> buildeSetUnmodif(final T... values) {
return Collections.unmodifiableSet(buildSetModifTypeSafe(values));
// Or use Set.of("a", "b", "c") if you use Java 9
}
如果你为init传递一些值,这是很好的 使用其他方法 如果您不小心将类型与buildSetModif混合,则生成的T将 是什么?扩展对象,这可能不是你想要的,这不能发生在buildSetModifTypeSafe变体,这意味着buildSetModifTypeSafe(1,2, "a");不会编译
创建新哈希集时,coobird的answer效用函数的概括:
public static <T> Set<T> newHashSet(T... objs) {
Set<T> set = new HashSet<T>();
for (T o : objs) {
set.add(o);
}
return set;
}
可以使用静态块进行初始化:
private static Set<Integer> codes1=
new HashSet<Integer>(Arrays.asList(1, 2, 3, 4));
private static Set<Integer> codes2 =
new HashSet<Integer>(Arrays.asList(5, 6, 7, 8));
private static Set<Integer> h = new HashSet<Integer>();
static{
h.add(codes1);
h.add(codes2);
}