Java 數組動態擴容
Java中給數組動態擴容的方法,代碼如下: 1
import java.lang.reflect.Array;
2
3
/**
4
* 數組動態擴容
5
* @author Administrator
6
*
7
*/
8
public class ArrayGrow {
9
10
/**
11
* 動態給數組擴容
12
* @param obj 需要擴容的數組
13
* @param addLength 給數組增加的長度
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方法里的測試數據輸出結果如下:
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44



posted on 2010-01-30 09:45 wzhongyu 閱讀(2154) 評論(0) 編輯 收藏 所屬分類: Java學習