I will get right into the problem here. This is the method that I have so far:
public T[] getAllValues() {
Serializable[] result = new Serializable[sets.size()];
for (int i = 0; i < sets.size(); i++) {
result[i] = sets.get(i).getValue();
}
return (T[]) result;
}
'T' is a parameterized type that extends Serializable. 'sets' is an ArrayList holding a type that stores both a String (key) and a T (value), so getValue() returns a T. In this method, I want to return all Ts in an array, so what I would actually like to do looks more like this:
public T[] getAllValues() {
T[] result = new T[sets.size()];
for (int i = 0; i < sets.size(); i++) {
result[i] = sets.get(i).getValue();
}
return result;
}
So the Serializable array, that is casted to a T array was just an idea as a work-around, but does not work unfortunately. But at the same time, I cannot use the second version, because
new T[int];
is obviously not possible to construct when the type is parameterized. Why is that? And more importantly: How can I work around it?
Thank you in advance
EDIT: I solved the problem, this is what I came up with:
public T[] getAllValues(T[] typearray) {
for (int i = 0; (i < typearray.length) && (i < sets.size()); i++) {
typearray[i] = sets.get(i).getValue();
}
return typearray;
}