本帖最后由 石德志 于 2012-2-25 10:04 编辑
关于张孝祥老师Java高新技术中数组反射,经测试张老师的代码只能打印出一维数组Object和非数组Object的内容,请教打出任意维数数组的代码- import java.lang.reflect.Array;
- import java.util.Arrays;
- public class PrintArrayDemo {
- public static void main(String[] args) {
- int [] a1 = new int[]{1,2,3};
- int [][] a2 = new int[][]{{1,2,3},{4,5}};
- String [] a3 = new String[]{"a","b","c"};
-
-
- System.out.println(a1);
- System.out.println(a2);
- System.out.println(a3);
- /*打印结果为:
- [I@192d342
- [[I@6b97fd
- [Ljava.lang.String;@1c78e57*/
- System.out.println(Arrays.asList(a1));
- System.out.println(Arrays.asList(a2));
- System.out.println(Arrays.asList(a3));
- /*打印结果为:
- [[I@192d342]
- [[I@1e63e3d, [I@1004901]
- [a, b, c]*/
- printObject(a1);
- printObject(a2);/* 打印结果为:[I@1e63e3d
- [I@1004901*/
- printObject(a3);
- /*
- 打印结果为:1
- 2
- 3
- [I@1e63e3d
- [I@1004901
- a
- b
- c*/
-
- }
- public static void printObject(Object obj){
- Class cls=obj.getClass();
- if(cls.isArray()){
- int len =Array.getLength(obj);
- for(int i=0;i<len;i++){
- System.out.println(Array.get(obj, i));
- }
- }else{
- System.out.println(obj);
- }
-
- }
- }
复制代码 printObject(a2);/* 打印结果为:[I@1e63e3d
[I@1004901*/
打印不出二维数组的内容,如果是不知道维数的数组呢?怎么设计算法? |
|