Java Modifying array length

Source: Internet
Author: User

There is no API for modifying the length of an array in Java, where I provide two functions to modify the length of the array: Arrayaddlength () and Arrayreducelength (). See Code in detail.  [java] View Plaincopyprint?import Java.lang.reflect.Array;    /** * Description:this class is used to adjust array length. * @author E421083458 *&nbs p;*/ public class Arraytest {   /** * @param args */ public static void Main (String [] args) { int a[]= new int[]{0,1,2,3,4,5};  int b[]= new int[]{0,1,2,3,4,5};  a = (int[]) arrayaddlength ( a,2);  b = (int[]) arrayreducelength (b,2);  //out Print Array lenght  system.out.println (a.length);  for (int i=0;i<a.length;i++) { system.out.print (a[i]);  }  system.out.println ();    system.out.println (b.length);  for (int i=0;i<b.length;i++) { system.out.print (B[i]),  }  }  /** * Description: Array add length * @param oldarray * @param addlength * @return object */ public Static Object Arrayaddlength (Object Oldarray,int addlength) { class c = oldarray.getclass ();  if (!c.isarray () ) return null;  class ComponentType = C.getcomponenttype ();  int length = Array.getlength (Oldarray);  int newlength = length + addlength;  object NewArray = array.newinstance (componenttype,newlength);  system.arraycopy (oldarray,0,newarray,0,length);  return NewArray;  }  /** * description:array reduce lenght * @param oldarray * @param reducelength * @ Return object */ public Static object Arrayreducelength (Object Oldarray,int reducelength) { class c = old Array.getclass ();  if (!c.isarray ()) return null;  class ComponentType = C.getcomponenttype ();  int length = Array.getlength (Oldarray);  int newlength = length-reducelength;  object NewArray = array.newinstance (componenttype,newlength);  system.arraycopy (oldarray,0,newarray,0,newlength);  return NewArray; &nBSP;}  }  

Java modifies array length

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.