扩充当前array大小

package test;

import java.lang.reflect.Array;

import entities.Person;

public class Reflection4 {
	
	public static void main(String[] args) {
		Person[] ps = new Person[]{new Person("dada",20),new Person("hehe", 2),new Person("tongtong",3)};
		Object ps2=Reflection4.incrementArray(ps);
		Reflection4.listArray(ps2);
	}
	
	
	/**
	 * 扩展数组,里面的参数可以自己设置
	 */
	public static Object incrementArray(Object array) {
		Class elementType = array.getClass().getComponentType();
		int size = Array.getLength(array);
		Object newArray=null;
		newArray = Array.newInstance(elementType, size*2);
		for(int i=0;i<size;i++) {
			Object o = Array.get(array, i);
			Array.set(newArray, i, o);
		}
		System.out.println("数组增长之后的大小: "+Array.getLength(newArray));
		//也可以使用下面的方法去把原来的值给设置进扩展后的数组里面
//		System.arraycopy(array, 0, newArray, 0, size);
		
		return newArray;
	}
	
	/**
	 * 把数组给打印出来
	 * @param array
	 */
	public static void listArray(Object array) {
		int size = Array.getLength(array);
		for(int i=0;i<size;i++) {
			System.out.println(Array.get(array, i));
		}
	}
}

你可能感兴趣的:(扩充当前array大小)