post08
数组初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package com.isflee.c04_5_1_arrays;
public class Arrays { public static void main(String[] args) { int[] a1 = { 1, 2, 3, 4, 5 }; int[] a2; a2 = a1; for(int i = 0; i < a2.length; i++) a2[i]++; for(int i = 0; i < a1.length; i++) prt("a1[" + i + "] = " + a1[i]); } static void prt(String s) { System.out.println(s); } }
|
1.基本数据类型的数组, 成员不进行赋值时会被自动初始化成对应基本数据类型的默认值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package com.isflee.c04_5_3_array_new;
import java.util.Random;
public class ArrayNew { static Random rand = new Random(); static int pRand(int mod) { return Math.abs(rand.nextInt()) % mod + 1; } public static void main(String[] args) { int[] a; a = new int[pRand(20)]; prt("length of a = " + a.length); for(int i = 0; i < a.length; i++) prt("a[" + i + "] = " + a[i]); } static void prt(String s) { System.out.println(s); } }
|
2.非基本数据类型的数组, 成员必须进行初始化(创建对象), 否则会报错
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package com.isflee.c04_5_2_array_class_obj;
import java.util.Random;
public class ArrayClassObj { static Random rand = new Random(); static int pRand(int mod) { return Math.abs(rand.nextInt()) % mod + 1; } public static void main(String[] args) { Integer[] a = new Integer[pRand(20)]; prt("length of a = " + a.length); for(int i = 0; i < a.length; i++) { a[i] = new Integer(pRand(500)); prt("a[" + i + "] = " + a[i]); } } static void prt(String s) { System.out.println(s); } }
|
3.高级用法, 将数组的类型定义为Object(根类), 这种定义比较灵活且有用.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package com.isflee.c04_var_args;
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()}); } }
|