In addition to Commons Lang, you can do this with Guava's method Ints.toArray(Collection<Integer> collection).
Read full article from http://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java
List<Integer> list = ... int[] ints = Ints.toArray(list);
List<Integer> Ints.asList(int...)
The easiest way to do this is to make use of Apache Commons Lang. It has a handy ArrayUtils class that can do what you want. Use the toPrimitive method with the overload for an array of Integers.
List<Integer> myList;
... assign and fill the list
int[] intArray = ArrayUtils.toPrimitive(myList.toArray(new Integer[myList.size()]));
Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:
List<T>.toArray won't work because there's no conversion from Integer to int
- You can't use
int as a type argument for generics, so it would have to be an int-specific method (or one which used reflection to do nasty trickery).
No comments:
Post a Comment