Object[] Array conversion problem

Source: Internet
Author: User

1. For the sake of the column as an outer loop, I want to construct the ArrayList into a two-dimensional array, as follows:

......

ArrayList Result=getresult ();

int n=result.size ();

String[][] Myarray=new string[n][];//define a two-dimensional array

for (int i=0;i<n;i++)//construct two-dimensional array
{
Arraylisttemparray= (ArrayList) result.get (i);
Myarray[i]= (string[]) Temparray.toarray ();
}

......

The program can be compiled through.

But when running to myarray[i]= (string[]) Temparray.toarray (), it's strange to have a java.lang.ClassCastException error.

Spent a night, looked up n more information, finally finished. The question is now recorded for reference.

2. The matter starts from the beginning.

The ArrayList class extends Abstractlist and executes the list interface. ArrayList supports dynamic arrays that can grow as needed.

ArrayList is like the following constructor:
  
ArrayList ()
ArrayList (Collection c)
ArrayList (int capacity)

If the newarraylist () construct is called, its default capacity (initial capacity) is 10.

See ArrayList source code, which is defined in this way:

Publicarraylist () {
This (10);
}

The default initialization of the internal array size is 10. Why is it 10? I don't know. Maybe Sun thinks it's cool.

When the program compiles and executes Arraylist.toarray (), the array size remains capacity (10) when the ArrayList is converted to an array.

When the loaded data and the capacity value are unequal (less than capacity), for example, only 5 data is loaded, the subsequent (Capacity-size) objects in the array are set to NULL, when the array coercion type conversion, there are some problems, such as java.lang.ClassCastException anomalies.

The workaround is to re-set the actual size of the array using TrimToSize () after converting the ArrayList data to a number of assemblies.


3. The modified code of this example is as follows, which can be run smoothly:

for (inti=0;i<n;i++)//construct two-dimensional arrays
{
ArrayList temparray= (ArrayList) result.get (i);
Myarray[i]= (string[]) Temparray.toarray (newstring[0]); //Note the wording here
}

Take a look at the following and maybe you'll understand-

One of Arraylist.toarray ():

Public object[] ToArray () {
Object[] result = new Object[size];
System.arraycopy (elementdata, 0, result, 0, size);
return result;
}

Returns an array of ArrayList elements, note that although a new array is generated, the array elements and elements in the collection are shared, and the collection interface says this is safe, which is not strict.

The following example demonstrates this effect.

ArrayList al=newarraylist ();
Al.add (Newstringbuffer ("Hello"));
Object[] A=al.toarray ();
stringbuffersb= (StringBuffer) a[0];
Sb.append ("changed"); Changing the elements of an array also changes the elements in the original ArrayList
System.out.println (al.get (0));

Do not use string instead of StringBuffer, because string is a constant.


Arraylist.toarray () bis:

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;
}

It is possible that this method does not need to generate a new array, noting that if the array a is too large, it is only set to null at size.

If the array A is large enough, it will put all the data in, and the returned array is also pointing to the array, (the extra space in the array stores the null object); If it is not large enough, apply an array of the same type as the parameter, put the value in, and return.


4. On-line information one:

Public string[] Getplatformidlist ()

{
Vector result = new vector ();
Try
{
Statement stmt = Conn.createstatement ();
String sql = "Select PlatformID from Platform";
rs = stmt.executequery (SQL);
while (Rs.next ())
{
Result.add (rs.getstring (1));
}
if (result.size () > 0)
{
string[] str = (string[]) Result.toarray (); Appears classcastexception
return str;
}
Else
return null;
}
catch (Exception e)
{
System.err.println (e);
return null;
}
Finally
{
Try
{
Rs.close ();
Conn.close ();
}
catch (Exception E2)
{}
}
}

After the program was run, it was found that the vector class could not be converted directly to string[by ToArray () method object[].

It is possible to find a ToArray (t[] a) method with another parameter.

Change the statement to:

String[]str = (string[]) Result.toarray (newstring[1]); that is, tell the vector what type of array I want to get.

Recall, it should be 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.


5. Information on the Internet two:

Correct use of List.toarray ()--

In the program, often get a list, the program requires the corresponding assignment to an array, you can write the program:

Long [] L =new long[list.size ()];
For (Inti=0;i<list.size (); i++)
L[i] = (Long) list.get (i);

To write these code, it seems more cumbersome, in fact, List provides a ToArray () method.
But to use it badly, there will be classcastexceptiony anomalies. How exactly this is generated, and look at the code:

List List = new ArrayList ();
List.add (New Long (1)); List.add (New Long (2));
List.add (New Long (3)); List.add (New Long (4));
long[] L = (long[]) List.toarray ();
for (int i=0; i<l.length; i++)
System.out.println (L[i].longvalue ());

The red code will throw java.lang.ClassCastException.

Of course, in order to read the value, you can do this code:

Object [] A = List.toarray ();
for (int i=0;i<a.length;i++)
System.out.println (((Long) a[i]). Longvalue ());

But let the array lose the type information, this is not what we want.


The correct use of ToArray () is as follows:

1) long[] L = new long[<totalsize>];
List.toarray (l);

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

3) Long [] A = Newlong[<total size>];
Long [] L = (long []) List.toarray (a);

6. Summary and supplement:

The Java SDK Doc says:

Public object[] ToArray (object[] a)

A--the array into which the elements of this list am to was stored,if it is big enough; Otherwise, a new array of Thesame runtime type is allocated for Thispurpose.

If the array A is large enough, it will put all the data in, and the returned array is also pointing to the array, (the extra space in the array stores the null object); If it is not large enough, apply an array of the same type as the parameter, put the value in, and return.

Note that if you pass in a parameter of 9 size and there are 5 objects in the list, then the other four are probably null and should be used with special care.

7. Complete.

Object[] Array conversion problem

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.