Home > DeveloperSection > Forums > Best way to convert a collection into an array in java
Elizabeth Hall
Elizabeth Hall

Total Post:1

Posted on    October-08-2015 8:11 AM

 Java Java  Collection  Array 

 1 Reply(s)
 637  View(s)
Rate this:
I am trying to convert ArrayList into integer array, but its throwing CTE, Is it possible to convert directly a collection into an array i.e. is there any  build-in utility class or method for doing this thing only?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    October-08-2015 8:29 AM

Hi Elizabeth, 
There is nothing build-in to convert a collection to an array as far as i know.
You may need to create a method which use Iterator or listIterator(in case of list) and iterate on all the elements of the collection through it and convert it by type casting into prmitive type and assign the value in the array. Pass your collection inside this method. folloe below code :
public static int[] convertIntegers(List<Integer> integers)
    int[] ret = new int[integers.size()];
    Iterator<Integer> iterator = integers.iterator();
    for (int i = 0; i < ret.length; i++)
        ret[i] = iterator.next().intValue();
    return ret;

Don't want to miss updates? Please click the below button!

Follow MindStick