Tuesday, 31 July 2012

Java Generics III - Array Initialization, Static Methods, Extend Class & Interfaces

How to Initialize an Array of Generic Type?

The following code will not compile:
public class A<V> {

  private Set<V>[] sets;

  public A(int size) {
     sets = new HashSet<V>[size];
  }

}
The solution is to use a cast:
     sets = (Set<V>[]) new HashSet[size];

How to Make a Static Method Generic?

The following code indicates how to proceed:
public class B<T> {

    // Allowed
    public static <U> U myStaticMethod(U u) {
        return ...;
    }

    // Not allowed
    public static T myStaticMethod2(T t) {
        return ...;
    }

}

How to Make a Generic Extends a Class and Multiple Interfaces?

This is a generic wildcard issue. Considering a class C, and two interfaces I1 and I2:
public class D<T extends C & I1 & I2> {
    
    // ...

}

The class must precede the interfaces. A generic can only extends one class at most.

Part I  Part II   Part III   Part IV