View on GitHub

我的学习笔记

好记性不如烂笔头

5.8 数组初始化

5.5.1 可变参数列表

//:initialization/ArrayOfPrimitives.java
public class ArrayOfPrimitives{
    public static void main(String[] args) {
        int[] a1={1,2,3,4,5};
        //Initialize the array by copy from another array,
        //It only copy a reference
        int[] a2;  
        a2=a1;

        for(int item:a2) item+=1;
        for(int i=0;i<a1.length;i++)
            System.out.println("a1["+i+"] = "+a1[i]);
    }
}/*Output:
a1[0] = 1
a1[1] = 2
a1[2] = 3
a1[3] = 4
a1[4] = 5
*///:~
//:initalization/ArrayCLassObj.java
//Creating an array of noprimitive objects
import java.util.*;

public class ArrayClassObj{
    public static void main(String[] args) {
        Random rand=new Random(47);
        Integer[] a=new Integer[rand.nextInt(20)];
        System.out.println("Length of a = "+ a.length);

       for(int i=0;i<a.length;i++)
            a[i]=rand.nextInt(500); //Autoboxing
        System.out.println(Arrays.toString(a));
    }
}/*Output:
Length of a = 18
[55, 193, 361, 461, 429, 368, 200, 22, 207, 288, 128, 51, 89, 309, 278, 498, 361, 20]
*///:~
import java.util.Arrays;
//:initialization/ArrayInit.java
//Array initialization
public class ArrayInit{
    public static void main(String[] args) {
        Integer[] a={
            new Integer(1),
            new Integer(2),
            3, //Autoboxing
        };

        Integer[] b=new Integer[]{
            new Integer(1),
            new Integer(2),
            3,  //Autoboxing
        };

        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(b));
    }
}/*Oytput:
[1, 2, 3]
[1, 2, 3]
*///:~

P.S: 可以创建一个String对象数组,将其床底给另一个main()方法,以提供参数,用来替换传递给该main()方法的命令行参数

//:initialization/DynamicArray.java
//Array initialization
public class DynamicArray{
    public static void main(String[] args) {
        Other.main(new String[]{"fiddle","de","dum"});
    }
}

class Other{
    public static void main(String[] args) {
        for(String s:args)
            System.out.print(s+" ");
    }
}/*Output:
fiddle de dum
*/

5.5.1 可变参数列表