ToArray Method-Reprint

Source: Internet
Author: User

ToArray method may report null pointer exception and type conversion exception

Article One:

ArrayList provides a very handy way to convert a list to an array toarray. The ToArray has two overloaded methods:

1.list.toarray ();

2.list.toarray (t[] a);

For the first overloaded method, the list is converted directly to the object[] array;

The second method is to convert the list into an array of the type you want, and of course we'll use it as the same type as the list content.

Unidentified students like to use the first, is so written:

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

Result of a run, error:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; Cannot is cast to [Ljava.lang.String;

Why not convert object[] to string[] in a glance. The only thing that can be transformed is to take out every element and convert it, like this:

12345 object[] arr = List.toarray (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; for   ( int   i = 0 ; I < Arr.length; i++) {              string e = (String) arr[i]; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; system.out.println (e); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;

So the first refactoring method is not so easy.

In fact, when you convert the list world to an array, the second refactoring method is more convenient and uses the following:

12 String[] array =newString[list.size()];        list.toArray(array);

Chapter Two:

public class Test {

public static void Main (string[] args) {

list<string> list = new arraylist<string> ();

List.add ("1");

List.add ("2");

String[] tt = (string[]) List.toarray (new string[0]);

}

}

This code is OK, but we see string[] tt = (string[]) List.toarray (new string[0]) The parameters are very strange, but remove this parameter new String[0] but run the times wrong ...

Two Root cause Analysis

The study found that ToArray has two methods:

Public object[] ToArray () {

Object[] result = new Object[size];

System.arraycopy (elementdata, 0, result, 0, size);

return result;

}

The ToArray method without parameters is a constructed object array and then a copy of the data, at which time the transformation will produce classcastexception, which is the root cause of the above problem.

Public object[] ToArray (Object a[]) {

if (A.length < size)

A = (object[]) java.lang.reflect.Array.newInstance (A.getclass (). Getcomponenttype (), size); System.arraycopy (elementdata, 0, a, 0, size);

if (A.length > Size)

A[size] = null;

return A;

}

The ToArray method with parameters, based on the type of the parameter array, constructs an empty array of the corresponding type, which is the same length as the size of ArrayList, although the method itself returns the result in the form of an object array. However, because the componenttype used in constructing arrays are consistent with the componenttype that need to be transformed, there is no transformation exception.

Three Solutions

So you can refer to the following three ways when using ToArray

1. long[] L = new Long[<total size>];

List.toarray (l);

2. long[] L = (long[]) List.toarray (new long[0]);

3. long[] A = new Long[<total size>];

Long[] L = (long[]) List.toarray (a);

Four Further consideration

The elements in the container have been restricted by generics, and the elements should be treated as generic types, but not in the current Java, when the direct string[] TT = (string[]) List.toarray (), run an error. Recall that the forced type conversion in Java is only for a single object, and to be lazy, it is not possible to convert the entire array into an array of another type, which is similar to the one that needs to be initialized.

ToArray Method-Reprint

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.