我怎么能转换成一个Java的HashSet<整数GT;为原始int数组? [英] How can I convert a Java HashSet<Integer> to a primitive int array?

查看:298
本文介绍了我怎么能转换成一个Java的HashSet<整数GT;为原始int数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的HashSet<整数GT; 在这一堆整数的。我希望把它变成一个数组,但调用

  hashset.toArray();

返回 [对象] 。有没有更好的方式来将它转换为 INT 的数组不是通过手工的每一个元素遍历其它?我想将数组传递给

 无效DoSomething的(INT [] ARR)

这不会接受对象[]数组,即使我尝试铸像

  DoSomething的((INT [])hashSet.toArray());


解决方案

Apache的<一个href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html\"相对=nofollow> ArrayUtils 有这个(它仍然迭代<一个href=\"http://svn.apache.org/viewvc/commons/proper/lang/trunk/src/main/java/org/apache/commons/lang3/ArrayUtils.java?view=markup#l2817\"相对=nofollow>幕后中):

  DoSomething的(ArrayUtils.toPrimitive(hashset.toArray()));

他们总是以检查这样的事情的好地方。

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();

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)

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

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

解决方案

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;整数GT;为原始int数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆