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

(coll) Arrays.asList(x).toArray().getClass() should be Object[].class

    Details

      Backports

        Description

        FULL PRODUCT VERSION :
        java version "1.5.0_02"
        Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_02-b09)
        Java HotSpot(TM) Client VM (build 1.5.0_02-b09, mixed mode, sharing)


        ADDITIONAL OS VERSION INFORMATION :
        Linux itppc27 2.4.19-4GB #1 Mon Aug 4 23:38:42 UTC 2003 i686 unknown

        A DESCRIPTION OF THE PROBLEM :
        The Collection documentation claims that

            collection.toArray()

        is "identical in function" to

            collection.toArray(new Object[0]);

        However, the implementation of Arrays.asList does not follow this: If created with an array of a subtype (e.g. String[]), its toArray() will return an array of the same type (because it use clone()) instead of an Object[].

        If one later tries to store non-Strings (or whatever) in that array, an ArrayStoreException is thrown.

        Either the Arrays.asList() implementation (which may return an array of component type not Object) or the Collection toArray documentation (which does not allow argumentless toArray() to return arrays of subtypes of Object) is wrong.

        STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
        Execute code.

        EXPECTED VERSUS ACTUAL BEHAVIOR :
        EXPECTED -
        [Ljava.lang.Object;@10b62c9
        [Ljava.lang.Object;@82ba41

        ACTUAL -
        [Ljava.lang.String;@10b62c9
        [Ljava.lang.Object;@82ba41


        REPRODUCIBILITY :
        This bug can be reproduced always.

        ---------- BEGIN SOURCE ----------
        import java.util.*;


        public class ToArray
        {
            public static void main(String[] args)
            {
                List l = Arrays.asList(args);

                System.out.println(l.toArray());
                System.out.println(l.toArray(new Object[0]));
            }
        }

        ---------- END SOURCE ----------

        CUSTOMER SUBMITTED WORKAROUND :
        Only use toArray(Object[]).
        ###@###.### 2005-04-25 12:45:46 GMT

          Attachments

            Issue Links

              Activity

                People

                • Assignee:
                  martin Martin Buchholz
                  Reporter:
                  ndcosta Nelson Dcosta (Inactive)
                • Votes:
                  0 Vote for this issue
                  Watchers:
                  9 Start watching this issue

                  Dates

                  • Created:
                    Updated:
                    Resolved:
                    Imported:
                    Indexed: