Toarray of arraylist

Source: Internet
Author: User

Arraylist provides a convenient toarray method to convert a list into an array. Toarray has two methods for overloading:

1. List. toarray ();

2. List. toarray (T [] );

For the first overload method, the list is directly converted into an array of object;

The second method is to convert the list to the array of the type you need. Of course, when using the list, the list will be converted to the same type as the list content.

 

If you are not really fond of using the first one, you can write it like this:

1234567 ArrayList<String> list=new ArrayList<String>();        for (int i = 0; i < 10; i++) {            list.add(""+i);        }                 String[] array= (String[]) list.toArray();        

 

Result 1: An error is returned:

Exception in thread "Main" Java. Lang. classcastexception: [ljava. Lang. object; cannot be cast to [ljava. Lang. String;

 

The reason is clear at first glance. If you cannot convert object [] to string [], you can only retrieve each element and then convert it, as shown in the following code:

12345 Object[] arr = list.toArray();        for (int i = 0; i < arr.length; i++) {            String e = (String) arr[i];            System.out.println(e);        }

Therefore, the first refactoring method is not so easy.

In fact, when the list world is converted to an array, the second reconstruction method is more convenient. Its usage is as follows:

 

12 String[] array =new String[list.size()];        List. toarray (array); <br> Appendix. source code of the two reconstruction methods:

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.