DulcetAirman icon

Generic Array Creation

DulcetAirman | PRO | 02/19/13 11:36:00 AM UTC | 0 ⭐ | 627 👁️ | Never ⏰ | []
Java |

2.2 KB

|

None

|

0 👍

/

0 👎

package com.example.foo;
 
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
 
public class SomeClass {
 
  static class Generic<T> {
    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<String> hello = new Generic<String>("Hello");
    final Generic<String> world = new Generic<String>("World");
    {// <?> instead of <String>:
      Generic<?>[] a = { hello, world };
      System.out.println(Arrays.toString(a));
    }
    {// Simple array creation, unchecked:
      @SuppressWarnings("unchecked")
      Generic<String>[] a = new Generic[] { hello, world };
      System.out.println(Arrays.toString(a));
    }
    {// Creates a copy, length must be specified, unchecked:
      @SuppressWarnings("unchecked")
      Generic<String>[] 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<String>[] a = (Generic<String>[]) Array.newInstance(Generic.class, 2);
      a[0] = hello;
      a[1] = world;
      System.out.println(Arrays.toString(a));
    }
    {// Creates a copy, unchecked:
      @SuppressWarnings("unchecked")
      Generic<String>[] 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<String>[] a = asArray(hello, world);
      // With explicit type declaration:
      final Generic<String>[] a2 = SomeClass.<Generic<String>>asArray(hello, world);
      System.out.println(Arrays.toString(a));
    }
    {// Collection instead of Array:
      Collection<Generic<String>> a = Arrays.asList(hello, world);
      System.out.println(a.toString());
    }
  }
 
  /** @see Arrays#asList(Object...) */
  @SafeVarargs
  static <T> T[] asArray(T... elements) {
    return elements;
  }
 
}

Comments