TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
- //利用反射调整数组的长度
- import java.lang.reflect.*;
- import java.util.*;
- public class ArrayGrowTest
- {
- public static void main(String[] args)
- {
- int[] a = { 1, 2, 3 };
- a = (int[]) goodArrayGrow(a);//将数组的长度增加10
- arrayPrint(a);
- String[] b = { "Tom", "Dick", "Harry" };
- b = (String[]) goodArrayGrow(b);
- arrayPrint(b);
- System.out.println("下面调用将产生一个异常");
- b = (String[]) badArrayGrow(b);//强制转换出错
- }
-
- //将数组的长度增加10,错误的方法
- static Object[] badArrayGrow(Object[] a)
- {
- int newLength = a.length * 11 / 10 + 10;
- Object[] newArray = new Object[newLength];
- System.arraycopy(a, 0, newArray, 0, a.length);
- return newArray;
- }
- //将数组的长度增加10,正确的方法
- static Object goodArrayGrow(Object a)//要将参数类型定义为Object,而不是Object[]
- {
- Class cl = a.getClass();
- if (!cl.isArray()) return null;
- Class componentType = cl.getComponentType();
- int length = Array.getLength(a);
- int newLength = length * 11 / 10 + 10;
- Object newArray = Array.newInstance(componentType, newLength);
- System.arraycopy(a, 0, newArray, 0, length);
- return newArray;
- }
-
- static void arrayPrint(Object a)
- {
- Class cl = a.getClass();
- if (!cl.isArray()) return;
- Class componentType = cl.getComponentType();
- int length = Array.getLength(a);
- System.out.print(componentType.getName()
- + "[" + length + "] = { ");
- for (int i = 0; i < Array.getLength(a); i++)
- System.out.print(Array.get(a, i) + " ");
- System.out.println("}");
- }
- }
复制代码
运行结果:
c:> java ArrayGrowTest int[13] = { 1 2 3 0 0 0 0 0 0 0 0 0 0 }
java.lang.String[13] = { Tom Dick Harry null null null null null null null null null null }
下列调用将产生一个异常
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object;
at ArrayGrowTest.main(ArrayGrowTest.java:17)
源码下载:http://file.javaxxz.com/2014/10/30/235808515.zip |
|