RSS Feed for This PostCurrent Article

Java Generics Summary

A short note on Java Generics

  • Generics are not covariant.
   1: List<Integer> li = new ArrayList<Integer>();
   2: List<Number> ln = li; // illegal
  • Construction Delays
   1: public void doSomething(T param) { 
   2:   T copy = new T(param);  // illegal
   3: }
  • Constructing wildcard references
   1: class Foo {
   2:   public void doSomething(Set<?> set) {
   3:     Set<?> copy = new HashSet<?>(set);  // illegal
   4:   }
   5: }
  • Constructing arrays
   1: class ArrayList<V> {
   2:   private V[] backingArray;
   3:   public ArrayList() {
   4:     backingArray = new V[DEFAULT_SIZE]; // illegal
   5:   }
   6: }

 

   1: class ArrayList<V> {
   2:   private V[] backingArray;
   3:   public ArrayList() {
   4:     backingArray = (V[]) new Object[DEFAULT_SIZE]; 
   5:   }
   6: }

 

Alternatives

   1: public class ArrayList<V> implements List<V> {
   2:   private V[] backingArray;
   3:   private Class<V> elementType;
   4:  
   5:   public ArrayList(Class<V> elementType) {
   6:     this.elementType = elementType;
   7:     backingArray = (V[]) Array.newInstance(elementType, DEFAULT_LENGTH);
   8:   }
   9: }


Trackback URL


Sorry, comments for this entry are closed at this time.