Saturday, October 27, 2018

java - How to convert an ArrayList containing Integers to primitive int array?



I'm trying to convert an ArrayList containing Integer objects to primitive int[] with the following piece of code, but it is throwing compile time error. Is it possible to convert in Java?



List x =  new ArrayList();
int[] n = (int[])x.toArray(int[x.size()]);


Answer



You can convert, but I don't think there's anything built in to do it automatically:



public static int[] convertIntegers(List integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();

}
return ret;
}


(Note that this will throw a NullPointerException if either integers or any element within it is null.)



EDIT: As per comments, you may want to use the list iterator to avoid nasty costs with lists such as LinkedList:



public static int[] convertIntegers(List integers)

{
int[] ret = new int[integers.size()];
Iterator iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...