/**
@ Version 1.01 2007-12-07
@ Author rianbow
*/
Import java. Lang. Reflect .*;
Import java. util .*;
Public class arraygrowtest
{
Public static void main (string [] ARGs)
{
Int [] A = {1, 2, 3 };
A = (INT []) goodarraygrow ();
Arrayprint ();
String [] B = {"Tom", "dick", "Harry "};
B = (string []) goodarraygrow (B );
Arrayprint (B );
System. Out. println ("the following call will generate an exception .");
B = (string []) badarraygrow (B );
}
/**
This method attempts to grow an array by allocating
New array and copying all elements.
@ Param a array to grow
@ Return a larger array that contains all elements of.
However, the returned array has type object [], not
The same type as
*/
Static object [] badarraygrow (object [])
{
Int newlength = A. length * 11/10 + 10;
Object [] newarray = new object [newlength];
System. arraycopy (A, 0, newarray, 0, A. Length );
Return newarray;
}
/**
This method grows an array by allocating
New array of the same type and copying all elements.
@ Param a array to grow. This can be an object Array
Or a fundamental type array
@ Return a larger array that contains all elements of.
*/
Static object goodarraygrow (Object)
{
Class Cl = A. getclass ();
If (! Cl. isarray () return NULL;
Class componenttype = Cl. getcomponenttype ();
Int length = array. getlength ();
Int newlength = length * 11/10 + 10;
Object newarray = array. newinstance (componenttype, newlength );
System. arraycopy (A, 0, newarray, 0, length );
Return newarray;
}
/**
A convenience method to print all elements in an array
@ Param a array to print. can be an object Array
Or a fundamental type array
*/
Static void arrayprint (Object)
{
Class Cl = A. getclass ();
If (! Cl. isarray () return;
Class componenttype = Cl. getcomponenttype ();
Int length = array. getlength ();
System. Out. Print (componenttype. getname ()
+ "[" + Length + "] = {");
For (INT I = 0; I <array. getlength (a); I ++)
System. Out. Print (array. Get (A, I) + "");
System. Out. println ("}");
}
}