base/common/src/main/com/thesett/common/util/AbstractHeap.java
public <T> T[] toArray(T[] a)
    {
        int size = size();

        if (a.length < size)
        {
            a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
        }

        Iterator<E> it = iterator();
        Object[] result = a;

        for (int i = 0; i < size; i++)
        {
            result[i] = it.next();
        }

        if (a.length > size)
        {
            a[size] = null;
        }

        return a;
    }
public <T> T[] toArray(T[] a)
    {
        int size = size();

        if (a.length < size)
        {
            a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
        }

        Iterator<E> it = iterator();
        Object[] result = a;

        for (int i = 0; i < size; i++)
        {
            result[i] = it.next();
        }

        if (a.length > size)
        {
            a[size] = null;
        }

        return a;
    }
Returns an array containing all of the elements in this heap; the runtime type of the returned array is that of
the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new
array is allocated with the runtime type of the specified array and the size of this collection.

<p>If the collection fits in the specified array with room to spare (i.e., the array has more elements than the
collection), the element in the array immediately following the end of the collection is set to <tt>null</tt>.
This is useful in determining the length of the collection <i>only</i> if the caller knows that the collection
does not contain any <tt>null</tt> elements.)

<p>If this collection makes any guarantees as to what order its elements are returned by its iterator, this
method must return the elements in the same order.

<p>This implementation checks if the array is large enough to contain the collection; if not, it allocates a new
array of the correct size and type (using reflection). Then, it iterates over the collection, storing each object
reference in the next consecutive element of the array, starting with element 0. If the array is larger than the
collection, a <tt>null</tt> is stored in the first location after the end of the collection.

@param  a   The array into which the elements of the collection are to be stored, if it is big enough; otherwise,
a new array of the same runtime type is allocated for this purpose.
@param  <T> The type of the array.

@return an array containing the elements of the collection.

@throws NullPointerException if the specified array is <tt>null</tt>.
@throws ArrayStoreException  if the runtime type of the specified array is not a supertype of the runtime type of
every element in this collection.