2

Is there a fast (in terms of saving programmers time not the execution time of program) utility method in default java libraries (without any external 3rd util libs) which would enable to create primitive array from a primitive wrapper collection?

Example:

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

Without manually creating new array instance iterating over the collection myself?

If not for collection, even for List<Integer> would be nice.

ps-aux
  • 9,706
  • 17
  • 67
  • 117

2 Answers2

3

You can't, because you must at least check how you're going to convert a null Integer to a primitive value.

Even Guava and Apache Commons have to iterate on the object list to make the conversion internally.

Guava - 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

Leo
  • 6,177
  • 3
  • 28
  • 48
  • Yep, I know that wrapper being null is the biggest problem here. But nothing which couldn't be done with NullPointerException. I know there are utility libs like Apache Commons but I was interested in sdk way. Now I have confirmed there is none. – ps-aux Feb 26 '14 at 20:50
0

I found this link.. It converts the Integer List to int array ,but uses org.apache.commons.lang.ArrayUtils

Here is the link..

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

Hope it helps..

user3213851
  • 966
  • 2
  • 9
  • 22