This is kind of a limitation of generics. Instead just declare your array as Object[]
and cast the element you try to return. Something similar to what ArrayList
does.
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
where elementData
is
private transient Object[] elementData;
If you control what is going in, there's no problem.
I'm going to link the question and answer in Rohit's comment because it's brilliant.