在java中,将包装集合转换为原始数组
在Java中,将包装器集合转换为原始数组是一种常见的需求。但是,Java标准库中并没有直接提供将包装器集合转换为原始数组的方法。在这种情况下,我们可以使用第三方库来完成这个任务。
我在互联网上找到了一个链接,它展示了如何使用org.apache.commons.lang.ArrayUtils将Integer List转换为int数组。下面是该链接:
[https://javarevisited.blogspot.in/2013/05/how-to-convert-list-of-integers-to-int-array-java-example-tips.html](https://javarevisited.blogspot.in/2013/05/how-to-convert-list-of-integers-to-int-array-java-example-tips.html)
这个链接提供了一个示例代码,演示了如何使用ArrayUtils类的toPrimitive方法将Integer List转换为int数组。这个方法接受一个包装器类型的数组作为参数,并返回相应的原始类型数组。
希望这个链接对您有所帮助。
在Java中,我们无法直接将包装类的集合转换为原始数组。这是因为我们必须至少检查如何将null的包装类转换为原始值。即使是Guava和Apache Commons也必须在内部迭代对象列表进行转换。
在Guava中,我们可以使用Ints类的toArray方法将包装类集合转换为原始数组。具体链接为:https://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/primitives/Ints.html#toArray%28java.util.Collection%29
在Apache Commons中,我们可以使用ArrayUtils类的toPrimitive方法将Integer对象数组转换为原始数组。具体链接为:https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#toPrimitive%28java.lang.Integer[]%29
但是,即使使用这些工具库,我们仍然需要迭代对象列表进行转换。对于包装类为null的情况,我们需要通过NullPointerException来处理。
虽然有一些实用库可以提供这样的功能,例如Apache Commons,但是我对Java SDK本身是否提供了类似的功能很感兴趣。经过确认,我发现Java SDK本身并没有提供将包装类集合转换为原始数组的方法。