望尘轩中一盏茶

统计

留言簿

友情链接

阅读排行榜

评论排行榜

Java 数组动态扩容

Java中给数组动态扩容的方法,代码如下:
 1import java.lang.reflect.Array;
 2
 3/**
 4 * 数组动态扩容
 5 * @author Administrator
 6 *
 7 */

 8public 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 = {123};
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方法里的测试数据输出结果如下:
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

posted on 2010-01-30 09:45 wzhongyu 阅读(2144) 评论(0)  编辑  收藏 所属分类: Java学习


只有注册用户登录后才能发表评论。


网站导航:
 
我的便捷门:综合频道 数码频道 商城频道 电器频道 男人频道 女人频道 居家玩具 美容频道 饰品鞋包 食品频道 台湾馆频道