Arraygrowtest. Java

Source: Internet
Author: User

/**
@ 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 ("}");
}
}

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.