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.

Answers


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.


If you are implementing a "SortedList" class, it's probably in your best interest to maintain a sorted list internally, rather than relying on the toArray() method to sort them on the way out. In other words, users of the class may not use the toArray() method, but may instead use listIterator() to return an Iterator that is supposed to iterate over the elements of the list in the proper order.


Are you sure you need to implement List. It is often sufficient just to implement Iterable and Iterator.

public class SortedList<S extends Comparable<S>> implements Iterable<S>, Iterator<S> {

  private final Iterator<S> i;

  // Iterator version.
  public SortedList(Iterator<S> iter, Comparator<S> compare) {
    // Roll the whole lot into a TreeSet to sort it.
    Set<S> sorted = new TreeSet<S>(compare);
    while (iter.hasNext()) {
      sorted.add(iter.next());
    }
    // Use the TreeSet iterator.
    i = sorted.iterator();
  }

  // Provide a default simple comparator.
  public SortedList(Iterator<S> iter) {
    this(iter, new Comparator<S>() {

      public int compare(S p1, S p2) {
        return p1.compareTo(p2);
      }
    });
  }

  // Also available from an Iterable.
  public SortedList(Iterable<S> iter, Comparator<S> compare) {
    this(iter.iterator(), compare);
  }

  // Also available from an Iterable.
  public SortedList(Iterable<S> iter) {
    this(iter.iterator());
  }

  // Give them the iterator directly.
  public Iterator<S> iterator() {
    return i;
  }

  // Proxy.
  public boolean hasNext() {
    return i.hasNext();
  }

  // Proxy.
  public S next() {
    return i.next();
  }

  // Proxy.
  public void remove() {
    i.remove();
  }
}

You can then do stuff like:

for ( String s : new SortedList<String>(list) ) 

which is usually all that you want because TreeSet provides your sortedness for you.


Need Your Help

How to download data from a dynamic website using JavaScript?

download dynamic-websites web-database

I want to download some data from a dynamic website i.e. football match scores in real time. Can I do that by running a script on the website? If yes, please tell me how. Otherwise tell me how I ca...

Typing in autoresizing textarea keeps on focusing at the top of the element

javascript jquery textarea autoresize cursor-position

I have an expanding textarea. When the textarea has already expanded enough to reach the bottom of the window, the body flickers/scrolls back to the top of the textarea and you cannot see the last

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.