Java List to Array toArray(List from, int[] to)

Here you can find the source of toArray(List from, int[] to)

Description

Copy the given List to the specified Array at offset zero.

License

Open Source License

Parameter

Parameter Description
from the List to copy the data from.
to the array to copy the data to.

Return

an Array containing all elements of from .

Declaration

public static int[] toArray(List<Integer> from, int[] to) 

Method Source Code

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

import java.util.List;

public class Main {
    /**// www  . ja v a 2  s.  c o m
     * Copy the given List to the specified Array at offset zero.
     * If {@code to} is {@code null} or has not enough capacity to fully store all
     * elements in the specified List, a new one will be created and returned.
     * If {@code to} is able to contain all data in {@code from}, {@code to} will
     * be returned.
     *
     * @param from the List to copy the data from.
     * @param to   the array to copy the data to.
     * @return an Array containing all elements of {@code from}.
     */
    public static int[] toArray(List<Integer> from, int[] to) {
        if (to == null || to.length < from.size()) {
            to = new int[from.size()];
        }

        int i = 0;
        for (Integer element : from) {
            to[i++] = element;
        }

        return to;
    }

    /**
     * Copy the given List to the specified Array at offset zero.
     * If {@code to} is {@code null} or has not enough capacity to fully store all
     * elements in the specified List, a new one will be created and returned.
     * If {@code to} is able to contain all data in {@code from}, {@code to} will
     * be returned.
     *
     * @param from the List to copy the data from.
     * @param to   the array to copy the data to.
     * @return an Array containing all elements of {@code from}.
     */
    public static long[] toArray(List<Long> from, long[] to) {
        if (to == null || to.length < from.size()) {
            to = new long[from.size()];
        }

        int i = 0;
        for (Long element : from) {
            to[i++] = element;
        }

        return to;
    }
}

Related

  1. toArray(List list)
  2. toArray(List list)
  3. toArray(List list)
  4. toArray(List values)
  5. toArray(List enums)
  6. toArray(List l)
  7. toArray(List list)
  8. toArray(List list)
  9. toArray(List list)