Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4215201

Why is toArray(Object a[]) designed this way?

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Won't Fix
    • Icon: P4 P4
    • None
    • 1.2.0
    • core-libs



      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)
      ======================================================================

            jjb Josh Bloch
            dblairsunw Dave Blair (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: