Java中給數(shù)組動(dòng)態(tài)擴(kuò)容的方法,代碼如下:
1
import java.lang.reflect.Array;
2
3
/**
4
* 數(shù)組動(dòng)態(tài)擴(kuò)容
5
* @author Administrator
6
*
7
*/
8
public class ArrayGrow {
9
10
/**
11
* 動(dòng)態(tài)給數(shù)組擴(kuò)容
12
* @param obj 需要擴(kuò)容的數(shù)組
13
* @param addLength 給數(shù)組增加的長(zhǎng)度
14
* @return
15
*/
16
@SuppressWarnings("unchecked")
17
public static Object arrayGrow(Object obj, int addLength) {
18
Class clazz = obj.getClass();
19
if(!clazz.isArray()) {
20
return null;
21
}
22
Class componentType = clazz.getComponentType();
23
int length = Array.getLength(obj);
24
int newLength = length + addLength;
25
Object newArray = Array.newInstance(componentType, newLength);
26
System.arraycopy(obj, 0, newArray, 0, length);
27
return newArray;
28
}
29
30
public static void main(String[] args) {
31
int[] a = {1, 2, 3};
32
a = (int[]) arrayGrow(a, 3);
33
for (int i = 0; i < a.length; i++) {
34
System.out.print("a[" + i + "] = " + a[i] + " ");
35
}
36
System.out.println();
37
38
String[] b = {"Jade", "TT", "JadeLT"};
39
b = (String[]) arrayGrow(b, 3);
40
for (int i = 0; i < b.length; i++) {
41
System.out.print("b[" + i + "] = " + b[i] + " ");
42
}
43
}
44
}
main方法里的測(cè)試數(shù)據(jù)輸出結(jié)果如下:
a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 0 a[4] = 0 a[5] = 0
b[0] = Jade b[1] = TT b[2] = JadeLT b[3] = null b[4] = null b[5] = null