更新时间:2023-01-09 21:12:15
像这样:
Set<T> mySet = new HashSet<>(Arrays.asList(someArray));
在 Java 9+ 中,如果不可修改的集合是可以的:
In Java 9+, if unmodifiable set is ok:
Set<T> mySet = Set.of(someArray);
在 Java 10+ 中,泛型类型参数可以从数组组件类型中推断出来:
In Java 10+, the generic type parameter can be inferred from the arrays component type:
var mySet = Set.of(someArray);
小心
Set.of 抛出 IllegalArgumentException - 如果有任何重复someArray 中的元素.查看更多详细信息:https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#of(E...)
Set.of throws IllegalArgumentException - if there are any duplicate elements in someArray. See more details: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#of(E...)