【问题标题】:Creating primitive array out of wrapper collection in java [duplicate]在java中从包装器集合中创建原始数组[重复]
【发布时间】:2014-03-29 06:24:38
【问题描述】:

在默认的 java 库(没有任何外部 3rd util 库)中是否有一个快速(就节省程序员时间而不是程序的执行时间而言)实用方法,可以从原始包装器集合创建原始数组?

例子:

int[] array = magicMethod(Collection<Integer>);

不用自己手动创建新的数组实例迭代集合?

如果不是为了收藏,即使是List&lt;Integer&gt;也不错。

【问题讨论】:

  • toArray() 是方法
  • @Batty toArray() 返回对象数组,而不是原始数组。
  • @OP 很遗憾没有,这就是为什么 Guava 创建了自己的原始类型集合实现的原因之一。
  • 关于“快速”,您的基本显式循环解决方案将尽可能快。

标签: java collections


【解决方案1】:

您不能,因为您至少必须检查如何将 null Integer 转换为原始值。

即使是 Guava 和 Apache Commons 也必须在对象列表上进行迭代才能在内部进行转换。

番石榴 - http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/primitives/Ints.html#toArray%28java.util.Collection%29

Apache Commons - http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#toPrimitive%28java.lang.Integer[]% 29

【讨论】:

  • 是的,我知道 wrapper 为 null 是这里最大的问题。但没有什么是 NullPointerException 无法完成的。我知道有像 Apache Commons 这样的实用程序库,但我对 sdk 方式很感兴趣。现在我已经确认没有。
【解决方案2】:

我找到了这个链接。它将整数列表转换为整数数组,但使用 org.apache.commons.lang.ArrayUtils

这是链接..

http://javarevisited.blogspot.in/2013/05/how-to-convert-list-of-integers-to-int-array-java-example-tips.html

希望对你有帮助..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2015-06-21
    相关资源
    最近更新 更多