import java.util.Random; public class TestArray { static Random rand = new Random(); static int prand(int mod){ return Math.abs(rand.nextInt())%mod + 1; } public static void main(String[] args){ int[] arr = new int[prand(10)]; int[][][] b = new int[prand(10)][][]; } }
非基本数据类型数组的初始化:
1 2 3 4 5 6 7 8 9 10 11 12
//java 1.0 Integer[] c1 = { new Integer(1), new Integer(2), new Integer(3),//最后这个逗号是可选的,(这一特性是长列表的维护变得更加容易) }; //java 1.1 Integer[] c2 = new Integer[]{ new Integer(1), new Integer(2), new Integer(3), };
class A{ int i; } public class Varargs { static void f(Object[] x){ for(int i=0; i<x.length; i++){ System.out.println(x[i]); } } public static void main(String[] args){ f(new Object[]{ new Integer(47), new Varargs(), new Float(3.14), new Double(11.11) }); f(new Object[]{ "one", "two", "three" }); f(new Object[]{ new A(), new A(), new A() //第一个输出: pers.wxy.hello.test.A@12edcd21 }); } }
多维数组
下面这个例子揭示出构成矩阵的每个矢量都是可以有任意长度的:
1 2 3 4 5 6 7
int[][][] a = new int[prand(10)][][]; for(int i=0; i<a.length; i++){ a[i] = new int[prand(10)][]; for(int j=0; j<a[i].length; j++){ a[i][j] = new int[prand(10)]; } }