M
Mike Schilling
Fooling around with generics, trying to create a type-safe list-like class,
and started with the following:
public class Glist<T>
{
private Class<T> etype;
private T[] elements;
public Glist(Class<T> cls, int size)
{
etype = cls;
// the next line gets an unchecked warning
elements = (T[]) java.lang.reflect.Array.newInstance(cls, size);
}
public T get(int i)
{
return elements;
}
public void set(T t, int i)
{
elements = t;
}
}
Which is fine, other than the redundancy in calls to the constructor, e.g.:
Glist<String> g = new Glist<String>(String.class, 10);
except for the unchecked warning. I looked at the Javadoc for both String
and Arrays, but couldn't find a type-safe way to create an array from a
Class instance. Am I missing something?
and started with the following:
public class Glist<T>
{
private Class<T> etype;
private T[] elements;
public Glist(Class<T> cls, int size)
{
etype = cls;
// the next line gets an unchecked warning
elements = (T[]) java.lang.reflect.Array.newInstance(cls, size);
}
public T get(int i)
{
return elements;
}
public void set(T t, int i)
{
elements = t;
}
}
Which is fine, other than the redundancy in calls to the constructor, e.g.:
Glist<String> g = new Glist<String>(String.class, 10);
except for the unchecked warning. I looked at the Javadoc for both String
and Arrays, but couldn't find a type-safe way to create an array from a
Class instance. Am I missing something?