1
public interface Foo<E> {

    public void blah(E e);

}

public class MyClass<E> {

    private final Foo<E>[] fooArray = new Foo<E>[8]; // does not compile!

    // (...)

}

What is the correct way of addressing that generics limitation?

Or maybe it is not a limitation and I am missing something?

The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
chrisapotek
  • 6,007
  • 14
  • 51
  • 85

1 Answers1

2

The make-it-compile way would be declaring the variable using generics but initializing the array (not the elements) using raw type:

//add @SuppressWarnings("unchecked") to avoid warnings
Foo<String>[] arrayOfFoo = new Foo[8];
arrayOfFoo[0] = new ClassThatImplementsFoo<String>();
//line below gives a compile error since the array declaration is for Foo<String>
//and won't allow Foo<AnotherClass>
arrayOfFoo[1] = new ClassThatImplementsFoo<Integer>();

A better and safer approach would be using List instead of plain array:

List<Foo<String>> fooList = new ArrayList<Foo<String>>();
fooList.add(new ClassThatImplementsFoo<String>());

In your code, you should do this:

public class MyClass<E> {
    private final Foo<E>[] fooArray = new Foo[8];
    // (...)
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332