previous | start | next

## Limitations of Generics

- Cannot replace type variables with primitive types
- Cannot construct new objects of generic type
  `a.add(new E()); // Error--would erase to new Object()`
- Workaround: Use class literals

      public static <E> void fillWithDefaults(ArrayList<E>,
         Class<? extends E> cl, int count)
         throws InstantiationException, IllegalAccessException
      {
         for (int i = 0; i < count; i++)
            a.add(cl.newInstance());
      }

- Call as `fillWithDefaults(a, Rectangle.class, count)`

previous | start | next