Extended array Length Using Reflection, reflected array Length

Source: Internet
Author: User

Extended array Length Using Reflection, reflected array Length
Extended array Length Using Reflection

Idea: to extend the array length is actually to generate a new array to overwrite the old array.

Import java. lang. reflect. *; public class Answer {public static void main (String [] args) {Test test = new Test (); test. print (); // print the content of the array test. is = (int []) addArrayLength (test. is, 10); // overwrite the old array test with the new array. ss = (String []) addArrayLength (test. ss, 10); test. print ();} public static Object addArrayLength (Object array, int newLength) {Object newArray = null; Class componentType = array. getClass (). getComponentType (); // obtain the class Object newArray = Array of an Array. newInstance (componentType, newLength); // dynamically creates an array System. arraycopy (array, 0, newArray, 0, Array. getLength (array); // returns newArray;} class Test {public int [] is = {1, 2, 3 }; public String [] ss = {"A", "B", "C"}; public void print () {for (int index = 0; index <is. length; index ++) {System. out. println ("is [" + index + "] =" + is [index]);} System. out. println (); for (int index = 0; index <ss. length; index ++) {System. out. println ("ss [" + index + "] =" + ss [index]);} System. out. println ();}}

Note:

Array. getClass (). getComponentType () to get an array class Object
Array. newInstance (componentType, newLength) dynamically creates an Array of the specified type
System. arraycopy (array, 0, newArray, 0, Array. getLength (array) implements copying between arrays. These five parameters represent the copied array, starting position, copying array, starting position, and length.

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.