Hi guys,
I need to turn a List (an ArrayList specifically) into an array of Components.
This is because I can't call a function like doSomething(Component ... components) with a collection. It needs to be an array correct?
So, if it needs to be an array, I can't find a clean way to do it....or maybe I'm just a whiner.
I can do this with
theList.toArray(new Component[theList.size()]);
or I can do it with
(Component[])theList.toArray()
But I don't like either of those...why should I have to pass an array in the first one and why should I be the one doing the cast in the second one?
Shouldn't the ArrayList know how to return a correctly typed array?
I wrote this little static method that I put in a helper class...does anything like this exist in the Collections class as a static method?
I couldn't find anything like it in Arrays, or Collections etc.
public static <T> T[] collectionToArray(Collection<T> l){
Object ret[] = new Object[l.size()];
int i = 0;
for(T t : l){
ret[i++] = t;
}
return (T[]) ret;
}
If there is a better way to do this please let me know.
Thanks,
~Eric