Advertisement
DulcetAirman

Generic Array Creation

Feb 19th, 2013
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. package com.example.foo;
  2.  
  3. import java.lang.reflect.Array;
  4. import java.util.Arrays;
  5. import java.util.Collection;
  6.  
  7. public class SomeClass {
  8.  
  9.   static class Generic<T> {
  10.     final T foo;
  11.  
  12.     public Generic(T foo) {
  13.       this.foo = foo;
  14.     }
  15.  
  16.     @Override
  17.     public String toString() {
  18.       return String.valueOf(foo);
  19.     }
  20.   }
  21.  
  22.   public static void main(String[] args) {
  23.     final Generic<String> hello = new Generic<String>("Hello");
  24.     final Generic<String> world = new Generic<String>("World");
  25.     {// <?> instead of <String>:
  26.       Generic<?>[] a = { hello, world };
  27.       System.out.println(Arrays.toString(a));
  28.     }
  29.     {// Simple array creation, unchecked:
  30.       @SuppressWarnings("unchecked")
  31.       Generic<String>[] a = new Generic[] { hello, world };
  32.       System.out.println(Arrays.toString(a));
  33.     }
  34.     {// Creates a copy, length must be specified, unchecked:
  35.       @SuppressWarnings("unchecked")
  36.       Generic<String>[] a = Arrays.copyOf(new Object[] { hello, world }, 2, Generic[].class);
  37.       System.out.println(Arrays.toString(a));
  38.     }
  39.     {// Can't be initialized by a list, length must be specified, unchecked:
  40.       @SuppressWarnings("unchecked")
  41.       Generic<String>[] a = (Generic<String>[]) Array.newInstance(Generic.class, 2);
  42.       a[0] = hello;
  43.       a[1] = world;
  44.       System.out.println(Arrays.toString(a));
  45.     }
  46.     {// Creates a copy, unchecked:
  47.       @SuppressWarnings("unchecked")
  48.       Generic<String>[] a = (Generic[]) Arrays.asList(hello, world).toArray();
  49.       System.out.println(Arrays.toString(a));
  50.     }
  51.     {// Method must be defined an called:
  52.       // Type defined by parameters and by type of variable (implicit):
  53.       Generic<String>[] a = asArray(hello, world);
  54.       // With explicit type declaration:
  55.       final Generic<String>[] a2 = SomeClass.<Generic<String>>asArray(hello, world);
  56.       System.out.println(Arrays.toString(a));
  57.     }
  58.     {// Collection instead of Array:
  59.       Collection<Generic<String>> a = Arrays.asList(hello, world);
  60.       System.out.println(a.toString());
  61.     }
  62.   }
  63.  
  64.   /** @see Arrays#asList(Object...) */
  65.   @SafeVarargs
  66.   static <T> T[] asArray(T... elements) {
  67.     return elements;
  68.   }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement