"Java" ArrayList into a string array problem __java

Source: Internet
Author: User

Java Container Class Collections ToArray () method, can transform such as arraylist<string> dynamic array, indefinite length of static array, fixed-length array string[]

However, the conversion method is wrong.

String[] Strarray = (string[]) Arraylist.toarray ();
If this execution results in the following error:

Exception in thread "XX" java.lang.ClassCastException: [Ljava.lang.Object; cannot being cast to [Ljava.lang.String;

The following figure:


The correct way should be written:

String[] Strarraytrue = (string[]) Arraylist.toarray (new string[0));
For example, the following procedure is normal:

Import java.util.*;

public class Arraylisttostrarr {public

	static void Main (string[] args) {
		arraylist<string> ArrayList = new Arraylist<string> ();
		Arraylist.add ("1");
		Arraylist.add ("2");
		Correct conversion Mode
		string[] strarraytrue = (string[]) Arraylist.toarray (new string[0));
		for (String str:strarraytrue) {
			System.out.println (str);
		}
		Incorrect conversion mode
		//string[] Strarray = (string[]) Arraylist.toarray ();

	}


Similarly extended to array arraylist<integer>, etc.

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.