本文介绍了如何转换 Java HashSet<Integer>到原始 int 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 HashSet,里面有一堆 Integers.我想把它变成一个数组,但是调用

I've got a HashSet<Integer> with a bunch of Integers in it. I want to turn it into an array, but calling

hashset.toArray();

返回一个 Object[].除了手动遍历每个元素之外,是否有更好的方法将其转换为 int 数组?我想将数组传递给

returns an Object[]. Is there a better way to cast it to an array of int other than iterating through every element manually? I want to pass the array to

void doSomething(int[] arr)

不会接受 Object[] 数组,即使我尝试像

which won't accept the Object[] array, even if I try casting it like

doSomething((int[]) hashSet.toArray());

推荐答案

Apache 的 ArrayUtils 有这个(它仍然迭代 幕后):

Apache's ArrayUtils has this (it still iterates behind the scenes):

doSomething(ArrayUtils.toPrimitive(hashset.toArray()));

他们总是检查此类事情的好地方.

They're always a good place to check for things like this.

这篇关于如何转换 Java HashSet&lt;Integer&gt;到原始 int 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:24