Java Array From toArray(final T... items)

Here you can find the source of toArray(final T... items)

Description

Create a type-safe generic array.

The Java language does not allow an array to be created from a generic type:

 public static <T> T[] createAnArray(int size) { return new T[size]; // compiler error here } public static <T> T[] createAnArray(int size) { return (T[])new Object[size]; // ClassCastException at runtime } 

Therefore new arrays of generic types can be created with this method.

License

Open Source License

Parameter

Parameter Description
T the array's element type
items the varargs array items, null allowed

Return

the array, not null unless a null array is passed in

Declaration

public static <T> T[] toArray(final T... items) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from w w  w .ja  v a2  s. com*/
     * <p>Create a type-safe generic array.</p>
     *
     * <p>The Java language does not allow an array to be created from a generic type:</p>
     *
     * <pre>
     public static &lt;T&gt; T[] createAnArray(int size) {
     return new T[size]; // compiler error here
     }
     public static &lt;T&gt; T[] createAnArray(int size) {
     return (T[])new Object[size]; // ClassCastException at runtime
     }
     * </pre>
     *
     * <p>Therefore new arrays of generic types can be created with this method.
     * For example, an array of Strings can be created:</p>
     *
     * <pre>
     String[] array = ArrayUtils.toArray("1", "2");
     String[] emptyArray = ArrayUtils.&lt;String&gt;toArray();
     * </pre>
     *
     * <p>The method is typically used in scenarios, where the caller itself uses generic types
     * that have to be combined into an array.</p>
     *
     * <p>Note, this method makes only sense to provide arguments of the same type so that the
     * compiler can deduce the type of the array itself. While it is possible to select the
     * type explicitly like in
     * <code>Number[] array = ArrayUtils.&lt;Number&gt;toArray(Integer.valueOf(42), Double.valueOf(Math.PI))</code>,
     * there is no real advantage when compared to
     * <code>new Number[] {Integer.valueOf(42), Double.valueOf(Math.PI)}</code>.</p>
     *
     * @param  <T>   the array's element type
     * @param  items  the varargs array items, null allowed
     * @return the array, not null unless a null array is passed in
     * @since  3.0
     */
    public static <T> T[] toArray(final T... items) {
        return items;
    }
}

Related

  1. toArray(final double d)
  2. toArray(final int ip)
  3. ToArray(final Object... toSmashIntoArray)
  4. toArray(final String[] strings)
  5. toArray(final T... array)
  6. toArray(final Throwable throwable)
  7. toArray(float[] floatArray)
  8. toArray(int arg1)
  9. toArray(int time)