The ToArray method of Java's ArrayList

Source: Internet
Author: User

ArrayList is a very high-frequency method used in Java. When we use ArrayList, we often need to convert the objects in the ArrayList to an array.

Java has a good encapsulation of ArrayList, and only calls ArrayList's ToArray method to extract an array of objects from the ArrayList object.

ArrayList overloads the following two ToArray methods:

Public object[] ToArray () {         return arrays.copyof (elementdata, size);     }

Public <T> t[] ToArray (t[] a) {         if (A.length < size)             return (t[]) arrays.copyof (elementdata, size, a.getc Lass ());          System.arraycopy (elementdata, 0, a, 0, size);         if (a.length > Size)             a[size] = null;         return A;     }

Beginners will encounter some confusion in the use of these two methods. The following combination of the author's own learning process encountered in the confusion for everyone to introduce these two toarray methods.

I have seen the following simple code on the Web when I was a beginner

  ArrayList List1 = new ArrayList ();  SYSTEM.OUT.PRINTLN ("Size:" + list1.size ());  for (int i=0; i<20; i++) {   list1.add ("Hello");  }  string[] str = (string[]) List1.toarray ();
The code above constructs a ArrayList object, then fills in 20 string objects, and finally wants to convert the objects in ArrayList into an array.

Executing the above code will report the following exception

[Ljava.lang.Object; Cannot is cast to [Ljava.lang.String;


The array returned by the ToArray () method is an object array. The above code casts an object array into a string array, which is a reference to forcing the reference of the parent class into a subclass.
In Java, this parent class reference is coerced into a subclass reference only if the reference to the parent class refers to the type of subclass that the real object is being coerced into, and the error is not made.
Here is a small example to illustrate.

Class father{string Name;int age;} Class Son extends father{string girlfriend;} Class daughter extends father{string boyfriend;} public class Test{public static void Main (string[] args) {Father f = new Son (); son s = (son) f;daughter d = (daughter) F; Father F2 = new Father (); Son s2 = (son) F2;}}

string[] str = (string[]) List1.toarray (); The error is probably due to the fact that the object returned by the ToArray () method is an array of object.

The source code for the arrays.copyof (elementdata, size) method is

public static <T,U> t[] CopyOf (u[] original, int newlength, class<? extends t[]> NewType) {      t[] copy = ((O bject) NewType = = (Object) object[].class)          ? (t[]) new Object[newlength]          : (t[]) array.newinstance (Newtype.getcomponenttype (), newlength);      System.arraycopy (original, 0, copy, 0,                       math.min (Original.length, newlength));      return copy;  }  public static <T> t[] CopyOf (t[] original, int newlength) {  return (t[]) copyOf (original, Newlength, original.ge Tclass ());  }  


It was observed that when the data type of the copy was not specified, copyof would directly copy the object using the data type of the source.

View ArrayList source code can see the definition of Elementdata as

Private transient object[] Elementdata;
Therefore, the ToArray () method returns an object with a true type of object[], so the type cannot be coerced to string [], and even if the ArrayList uses generics, a similar coercion of type conversions is not possible.

We typically convert ArrayList to an array of target types through the ToArray (t[] contents) method

ToArray (t[] contents) Call mode a public static integer[] VectorToArray1 (arraylist<integer> v) {integer[] NewText = new Integer[v.size ()]; V.toarray (NewText); return NewText;} ToArray (t[] contents) call mode two. Most commonly used! public static integer[] VectorToArray2 (arraylist<integer> v) {integer[] NewText = (integer[]) V.toarray (new Integer[0]); return NewText;} ToArray (t[] contents) Call way three public static integer[] VectorToArray3 (arraylist<integer> v) {integer[] NewText = new Integer[v.size ()]; Integer[] Newstrings = (integer[]) V.toarray (NewText); return newstrings;}


Public <T> t[] ToArray (t[] a) {         if (A.length < size)             return (t[]) arrays.copyof (elementdata, size, a.getc Lass ()); # method Two          system.arraycopy (elementdata, 0, a, 0, size); # method One and method three         if (a.length > Size)             a[size] = null;         return A;     }

The first and third methods use the System.arraycopy statement in the ToArray (t[] contents) method to copy the array. Because the system.arraycopy directly changed

The target array refers to the contents, so you can do the same as method one without having to define the return value of the ToArray method, return the return value, and return the target array directly.

Method two uses the ARRAY.COPYOF statement in the ToArray (t[] contents) method to recreate an array of the target type.

Because the statement of method Two is more concise, method Two is more commonly used.





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The ToArray method of Java's ArrayList

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.