Example analysis of list and array conversion in Java _java

Source: Internet
Author: User

In this paper, we analyze the conversion between list and array in Java. Share to everyone for your reference. Specifically as follows:

Writing code today encountered a strange problem, the specific code does not post, write a simplified version. As follows:

Arraylist<string> list=new arraylist<string> ();
String strings[]= (String []) List.toarray ();

This writing code personally feel that there should be no problem, the compilation is no problem. However, when the specific operation of the report abnormal, as follows: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object;

But there is no problem with this:

Arraylist<string> list=new arraylist<string> ();
String strings[]=new string[list.size ()];
for (int i=0,j=list.size (); i<j;i++) {
  strings[i]=list.get (i);
}

We can explain this in this way: Java allows for up and down transitions, but the success of this transition is based on the type of object in the Java virtual machine. The type of each object is saved in the Java virtual machine. An array is also an object. The type of the array [Ljava.lang.Object. convert [Ljava.lang.Object to [ Ljava.lang.String is obviously impossible, because here is a downward transition, and the virtual machine only saves this is an array of object, does not guarantee that the elements in the array are string, so this transformation cannot succeed. The elements in an array are just references to elements, not specific elements of the store, so the type of elements in the array is stored in the Java Virtual machine.

Based on the above explanation, we can generalize this problem to the following model:

Object objs[]=new object[10];
String strs[]= (string[]) Objs;

This is the same as the compilation error just above. If we modify this code, this is as follows:

String strs[]=new string[10];
Object Objs[]=strs;

This way can be compiled through. So we can boil down to the problem of a Java transition rule. Let's talk about Java array support for generics.

There is already support for generics in JDK5, which guarantees the security of data types in collections and maps, but the list's ToArray method returns an object [] that is confusing. The individual senses should be able to return the corresponding T [] directly according to the paradigm. Take a closer look at the JDK's source code Discovery list has two ways to convert to array:

Public object[] ToArray ();

This method returns all the elements in the list to an array of the same size, and all elements in the array are of type object.

Public <T> t[] ToArray (t[] a);

This method returns all the elements in the list to an array of the same size, and all elements in the array are of type T.

The list is so designed because the Java compiler does not allow us to new generic arrays. Which means you can't define an array like this:

T Arr=new T[size];

But you can use t[to represent the array, and you can force the array into t[]. For example, public <T> t[] ToArray (t[] A in the list is so implemented:

Public <T> t[] ToArray (t[] a) {
 if (A.length < size)
   a = (t[)) 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;
}

As you can see from the code above, because you don't know the type of the array, you have to create the array through the reflection mechanism (A.getclass (). The Getcomponenttype () method is to get the type of an array element).
Finally, the list can be converted to array to handle this:

Arraylist<string> list=new arraylist<string> ();
String[] strings = new string[list.size ()];
List.toarray (strings);

Conversely, what if you want to turn an array into a list? As follows:

String[] s = {"A", "B", "C"};
List List = Java.util.Arrays.asList (s);

I hope this article will help you with your Java programming.

Related Article

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.