Hello. It's been a while since I was on here.
I'm writing a Java class with a generic type parameter. Among other things, it maintains an internal ArrayList of the same generic type as itself. In a perfect world, the code would go like this:
import java.util.ArrayList;
public class MyGenericClass<T> {
private ArrayList<T> items;
public MyGenericClass() {
items = new ArrayList<T>();
}
}
Unfortunately, we do not live in a perfect world, and this doesn't work because of type erasure.
The only solution I can think of is to instantiate a raw ArrayList. (This will never result in a ClassCastException; I can guarantee that no non-T objects will ever be stored in the ArrayList.) However, I know that this is not good practice; in fact, I've actually heard from more than one authoritative source that raw types should never be instantiated except in legacy code.
Is there a better way? Thanks for your time.