BEST WAY TO CONVERT A COLLECTION INTO AN ARRAY IN JAVA

Elizabeth Hall

Total Post:1

Points:7
Posted by  Elizabeth Hall
 663  View(s)
Ratings:
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?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Best way to convert a collection into an array in java

    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;
    }


Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!