Java Collection to Array toArray(Collection collection)

Here you can find the source of toArray(Collection collection)

Description

Transforms a Collection of Integer instances to a simple int array.

License

Open Source License

Parameter

Parameter Description
collection a <code>Collection</code> of <code>Integer</code>s.

Return

an int array with the values from the specified collection.

Declaration

public static int[] toArray(Collection<Integer> collection) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Collection;
import java.util.Iterator;

public class Main {
    /**//from   ww  w  .j  a va 2s . com
     * A shared, empty and immutable integer array, which can be used to avoid
     * allocating empty integer arrays whenever one needs to present an empty
     * integer array.
     */
    public static final int[] EMPTY_ARRAY = new int[0];

    /**
     * Transforms a <code>Collection</code> of <code>Integer</code> instances
     * to a simple <code>int</code> array.
     * 
     * @param collection a <code>Collection</code> of <code>Integer</code>s.
     * @return an <code>int</code> array with the values from the specified
     *         <code>collection</code>.
     */
    public static int[] toArray(Collection<Integer> collection) {
        // check if we have an empty collection here
        if (collection.isEmpty())
            return EMPTY_ARRAY;
        // transform the collection into an array
        int[] array = new int[collection.size()];
        Iterator<Integer> iterator = collection.iterator();
        for (int n = 0; iterator.hasNext(); ++n)
            array[n] = iterator.next().intValue();
        return array;
    }
}

Related

  1. toArray(Collection collection)
  2. toArray(Collection tests)
  3. toArray(Collection list)
  4. toArray(Collection values)
  5. toArray(Collection values)
  6. toArray(Collection collection)
  7. toArray(Collection collection, Long defaultValue)
  8. toArray(Collection col)
  9. toArray(Collection collection)