views:

55

answers:

1

Here, I wondered about how to implement Collection#toArray(T[] array) properly. I was mostly annoyed that array.getClass().getComponentType() is of type Class<?> and not Class<? extends T> as I would have expected.

Therefore, I coded these three functions:

@SuppressWarnings("unchecked") static <T> Class<? extends T> classOf(T obj) {
    return (Class<? extends T>) obj.getClass();
}

@SuppressWarnings("unchecked") static <T> Class<? extends T> classOf(T[] array) {
    return (Class<? extends T>) array.getClass().getComponentType();
}

@SuppressWarnings("unchecked") static <T> T[] newArray(Class<T> clazz, int size) {
    return (T[]) Array.newInstance(clazz, size);
}   

And then, my toArray implementation looks like:

    public <T> T[] toArray(T[] array) { 
        int size = size();
        if (array.length < size) { 
            array = newArray(classOf(array), size);
        } else if (array.length > size) {
            array[size] = null;
        }

        int i = 0;
        for (E e : this) {
            array[i] = classOf(array).cast(e);
            i++;
        }
        return array;
    } 

What I wonder about now is:

Are these 3 helper functions always safe? Esp., is the cast always safe?

Why aren't these functions already in Java?

Also see this very related questions: T obj for a generic type T. The type of obj.getClass() is Class<?> and not Class<? extends T>. Why?

A: 

Your code looks pretty much OK, but you might consider using java.util.Arrays.copyOf to simplify your life.

Cameron Skinner