Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

List to Array with Type

843793Jun 20 2008 — edited Jun 21 2008
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 19 2008
Added on Jun 20 2008
5 comments
189 views