package com.example.foo; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collection; public class SomeClass { static class Generic { final T foo; public Generic(T foo) { this.foo = foo; } @Override public String toString() { return String.valueOf(foo); } } public static void main(String[] args) { final Generic hello = new Generic("Hello"); final Generic world = new Generic("World"); {// instead of : Generic[] a = { hello, world }; System.out.println(Arrays.toString(a)); } {// Simple array creation, unchecked: @SuppressWarnings("unchecked") Generic[] a = new Generic[] { hello, world }; System.out.println(Arrays.toString(a)); } {// Creates a copy, length must be specified, unchecked: @SuppressWarnings("unchecked") Generic[] a = Arrays.copyOf(new Object[] { hello, world }, 2, Generic[].class); System.out.println(Arrays.toString(a)); } {// Can't be initialized by a list, length must be specified, unchecked: @SuppressWarnings("unchecked") Generic[] a = (Generic[]) Array.newInstance(Generic.class, 2); a[0] = hello; a[1] = world; System.out.println(Arrays.toString(a)); } {// Creates a copy, unchecked: @SuppressWarnings("unchecked") Generic[] a = (Generic[]) Arrays.asList(hello, world).toArray(); System.out.println(Arrays.toString(a)); } {// Method must be defined an called: // Type defined by parameters and by type of variable (implicit): Generic[] a = asArray(hello, world); // With explicit type declaration: final Generic[] a2 = SomeClass.>asArray(hello, world); System.out.println(Arrays.toString(a)); } {// Collection instead of Array: Collection> a = Arrays.asList(hello, world); System.out.println(a.toString()); } } /** @see Arrays#asList(Object...) */ @SafeVarargs static T[] asArray(T... elements) { return elements; } }