Java.util.List.toArray () experience in using

Source: Internet
Author: User
Java.util.List.toArray () experience in usingTags: objectstringexceptionlistnull 2012-02-28 11:23 18713 people read Comments (0) Favorites Report Category: Android_ character processing (2)

Copyright NOTICE: This article is the original article of the blogger, without the permission of the blogger may not be reproduced.

After the following code executes:

[Java]  View plain  copy Private void onbuttonlisttoarrayclick ()  {        // array--->List       string[] strarray = new  String[] {  "AA",  "BB"  };       List<String>  List = new arraylist<string> (Arrays.aslist (strarray));        list.add ("CC");       // list--->Array        String[] strArray2;       try {            strArray2 =  (string[])  list.toarray ();        } catch  (exception e)  {          &NBSP;&NBSP;LOG.I ("ToArray",  "Failure:"  + e.getmessage ());       }      }  
Exception occurred


Because List.toarray () returns the object type, it occurs when the cast is classcastexception

The procedure is amended as follows:

[Java]  View plain  copy Private void onbuttonlisttoarrayclick ()  {        // array--->List       string[] strarray = new  String[] {  "AA",  "BB"  };       List<String>  List = new arraylist<string> (Arrays.aslist (strarray));        list.add ("CC");       // list--->Array        String[] strArray2 = null;       try {            strarray2 = list.toarray (new String[0]);        } catch  (exception e)  {       &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.I ("ToArray",  "Failure:"  + e.getmessage ());        }       for  (string element : strarray2)  {   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.I ("ToArray",  "StrArray2:"  + element);        }     }  
Run Result:


The method above

[Java] view plain Copy strArray2 = List.toarray (new string[0));
As with the following method

[Java] view plain copy strArray2 = new String[list.size ()];

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.