将 Set<Integer> 转换为原始数组

4
我正在使用以下代码将Set转换为int[]:
Set<Integer> common = new HashSet<Integer>();
int[] myArray = (int[]) common.toArray();

我遇到了以下错误:

 error: incompatible types: Object[] cannot be converted to int[]

什么是最干净的方法,在不使用 for 循环逐个添加元素的情况下进行转换?谢谢!

终于在 StackOverflow 上看到一个格式良好、语法正确的问题了。 - Tilak Madichetti
3个回答

9

通常你这样做:

Set<Integer> common = new HashSet<Integer>();
int[] myArray = common.stream().mapToInt(Integer::intValue).toArray();

兄弟,我想学习关于::运算符的知识,我应该从哪里学习? - Tilak Madichetti
@TilakMadichetti 这被称为“方法引用”。 在这里可以参考一下:https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html - xehpuk
intValue 是 Integer 类中的一个方法吗? - Tilak Madichetti
正确的链接:https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#intValue-- - xehpuk

7
Set<Integer> common = new HashSet<>();
int[] values = Ints.toArray(common);

Integer[] != int[] - xehpuk
现在已经改用Guava的辅助库。 - s7vr

2

您不能将某个内容显式地转换为数组。

请使用以下方法:

Integer[] arr = new Integer[common.size()];
Iterator<Integer> iterator = common.iterator(); 
int i = 0;
while (iterator.hasNext()){
    arr[i++] = iterator.next();
}

@tom 为什么代码无法编译? - Tilak Madichetti
@tom 现在会工作吗? - Tilak Madichetti
@Tom,请编辑我的答案 - Tilak Madichetti
什么是原始类型,为什么我们不应该使用它? - Tom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接