JDK-4215201 : Why is toArray(Object a[]) designed this way?
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 1.2.0
  • Priority: P4
  • Status: Closed
  • Resolution: Won't Fix
  • OS: generic
  • CPU: generic
  • Submitted: 1999-02-25
  • Updated: 2021-03-03
  • Resolved: 1999-03-04
Related Reports
Relates :  
Description

Name: dbT83986			Date: 02/25/99


Why this?:

public Object[] toArray(Object a[])
{
    if (a.length < size)
        a = (Object[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size) a[size] = null; 
    return a;
}

Now you must declare a new array first of the type you want.
  If you must do that why do it then not the way the Vector works
with copyInto. Declaring the array and the Vector copies everything in it.
  It can be so much easier.
  What do you want when
you want to use the above method?
  You want to get an array back that is of type Xxxxx class.
  So why not do exacly what
you want?

public Object[] toArray(Class c)
{
    if (a.length < size)
        a = (Object[])java.lang.reflect.Array.newInstance(c, size);
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size) a[size] = null;
    return a;
}

example:

public void main(String[] args)
{
    ArrayList al = new ArrayList()
    // Adding some values to the list (Strings)
    String[] strings = al.toArray(String.class);
}

So much simpler and easier to understand.
  But why isn't it designed this way?
  What am i missing?


greetings
johan compagner
(Review ID: 48036)
======================================================================

Comments
WORK AROUND Name: dbT83986 Date: 02/25/99 Write your own. ======================================================================
11-06-2004

EVALUATION The advantages of the signature: Object[] toArray(Object[]); over: Object[] toArray(Class); are two-fold: 1) It provides efficiency in the common case wherein the caller wants to reuse a buffer assuming it's big enough, and 2) It is consistent with proposals for adding parameterized classes to Java (such as GJ: http://www.cs.bell-labs.com/~wadler/pizza/gj/). joshua.bloch@Eng 1999-03-03
03-03-1999