Search code examples
javalisttoarray

T[] toArray(T[] a) implementation


I am creating a SortedList class that implements List.

If I understand correctly, the method toArray(T[] a) takes an array of objects as a parameter and returns a sorted array of these objects.

In the java documentation we can read that if the Collection length is greater than the sortedList, a new array is created with the good size, and if the collection length is smaller than the sortedList, the object following the last object of the collection is set to null.

The project I am working on does not let me use null values in the sorted list, so I am implementing the method differently, using a new sortedList and the toArray() method:

public <T> T[] toArray(T[] a)
{
    SortedList sort = new SortedList();

    for(Object o : a)
    {
        sort.add(o);
    }

    return (T[])sort.toArray();
}

Would this be a good way to implement this method or should I expect errors using it like that?

Thank you for your time.


Solution

  • First a recommendation:

    If you want SortedList to implement the List interface, it's a good idea to extend AbstractList instead of implementing List directly. AbstractList has already defined many of the necessary methods, including the one you're having problems with. Most List-implementations in the Java platform libraries also extend AbstractList.

    If you still want to implement List directly, here is what the method is supposed to do:

    Let a be the specified array.

    • If a is large enough, fill it with the elements from your SortedList (in the correct order) without caring about what was previously in a.
    • If there's room to spare in a after filling it, set a[size()] = null. Then the user will know where the list ends, unless the list contains null-elements.
    • If the list doesn't fit in a, create a new array of type T with the same size as the list, and fill the new one instead.
    • Return the array you filled. If you filled a, return a. If you made a new array, return the new array.

    There are two reasons why this method is useful:

    • The array will not necessarily be of type Object, but of a type T decided by the user (as long as the type is valid).
    • The user may want to save memory and re-use an array instead of allocating more mamory to make a new one.

    Here is how the Java Docs describe the method.