Title: Problems When arraylist uses toarray () to construct an array
Keywords: toarray construct an array
Author: jrq
Abstract: solves the problem of constructing an Array Using arraylist. toarray. Make a memo.
Link: http://blog.csdn.net/jrq/archive/2005/10/27/517428.aspx
Body:
1. In order to make an External Loop by column, we want to construct arraylist into a two-dimensional array, as shown below:
......
Arraylist result = getresult ();
Int n = result. Size ();
String [] [] myarray = new string [N] []; // defines a two-dimensional array
For (INT I = 0; I <n; I ++) // construct a two-dimensional array
{
Arraylist temparray = (arraylist) result. Get (I );
Myarray [I] = (string []) temparray. toarray ();
}
......
ProgramIt can be compiled.
However, when running to myarray [I] = (string []) temparray. toarray (), the Java. Lang. classcastexception error occurs, which is strange.
It took me one night to check n more materials and finally got it done. Record the problem for reference.
2. Start from scratch.
The arraylist class extends javasactlist and executes the list interface. Arraylist supports dynamic arrays that can grow as needed.
Arraylist has the following constructor:
Arraylist ()
Arraylist (collection C)
Arraylist (INT capacity)
If the new arraylist () construction is called, the default capacity (initial capacity) is 10.
See the arraylist source code, which is defined as follows:
Public arraylist (){
This (10 );
}
The size of the initialized internal array is 10 by default. Why 10? I don't know. Sun may think this is quite refreshing.
After the program is compiled, execute arraylist. toarray (). When arraylist is converted to an array, the size of the array is still capacity (10 ).
When the loaded data is not equal to the capacity value (less than capacity), for example, if only five data entries are loaded, the object (Capacity-size) after the array is set to null, at this time, some problems may occur when the array type conversion is forced, such as Java. lang. classcastexception and so on.
Solution: Use trimtosize () to re-set the true size of the array after converting data into several Arrays Using arraylist.
3. The modifiedCodeTo run smoothly:
For (INT I = 0; I <n; I ++) // construct a two-dimensional array
{
Arraylist temparray = (arraylist) result. Get (I );
Myarray [I] = (string []) temparray. toarray (New String [0]); // note the writing method here
}
Take a look at the following and you may 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 the arraylist element. Note that although a new array is generated here, the array elements are shared with the elements in the set. This is safe in the collection interface, this is not strict.
The following example demonstrates the effect.
Arraylist Al = new arraylist ();
Al. Add (New stringbuffer ("hello "));
Object [] A = Al. toarray ();
Stringbuffer sb = (stringbuffer) A [0];
SB. append ("changed"); // changing the array element also changes the element in the original arraylist.
System. Out. println (Al. Get (0 ));
Here, do not use string instead of stringbuffer, because string is a constant.
Arraylist. toarray () 2:
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;
}
This method may not need to generate a new array. Note that if the size of array a is too large, it is only set to null in the size field.
If array a is large enough, all the data will be put in, and the returned array also points to this array (the extra space of the array stores null objects); if it is not large enough, apply for an array of the same type as the parameter, put the value in, and then return.
4. Online materials 1:
Public String [] getplatformidlist ()
{
Vector result = new vector ();
Try
{
Statement stmt = conn. createstatement ();
String SQL = "select platformid from platform ";
Rs = stmt.exe cutequery (SQL );
While (Rs. Next ())
{
Result. Add (Rs. getstring (1 ));
}
If (result. Size ()> 0)
{
String [] STR = (string []) result. toarray (); // 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 runs, it is found that the object [] obtained by the toarray () method of the Vector class cannot be directly converted to string [].
Find another toarray (T [] A) method with parameters.
Change the statement:
String [] STR = (string []) result. toarray (New String [1]); that is, the type of the array I want to obtain indicates the vector.
In retrospect, it should be that the forced type conversion in Java is only for a single object. To be lazy, it is not feasible to convert the entire array into another type of array.
5. Online materials 2:
Use List. toarray () correctly ()--
In a program, a list is usually obtained. The program requires that the corresponding value be assigned to an array. You can write the program as follows:
Long [] L = new long [list. Size ()];
For (INT I = 0; I <list. Size (); I ++)
L [I] = (long) list. Get (I );
It seems complicated to write these codes. In fact, the List provides the toarray () method.
However, if the classcastexceptiony is not used properly, a classcastexceptiony exception occurs. See the code for how this is generated:
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, to read the value, you can Code as follows:
Object [] A = List. toarray ();
For (INT I = 0; I <A. length; I ++)
System. Out. println (long) A [I]). longvalue ());
However, the type information is lost in the array, which is not what we want.
The correct use of toarray () is as follows:
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 ();
6. Summary and supplement:
Java sdk doc:
Public object [] toarray (object [])
A -- the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
If array a is large enough, all the data will be put in, and the returned array also points to this array (the extra space of the array stores null objects); if it is not large enough, apply for an array of the same type as the parameter, put the value in, and then return.
Note that if the input parameter is 9 and the list contains 5 objects, the other four may be null.
7. Complete.
J. R. Q.
2005.10.27 am in Guangzhou