7.1声明数组变量的时候,不能指定数组的长度。如:int x[1]; 编译出错。
7.2对于Java类的程序入口方法main(String args[]),如果运行这个类时没有输入参数,那么main()方法的参数args并不是null,而是一个长度为0的数组。
public static void main(String[] args) {
System.out.println(args.length); //打印0
System.out.println(args); //打印[Ljava.lang.String;@de6ced
}
7.3数组对象的创建过程,如:int[] x = new int[3];
(1)在堆区中为数组分配空间。
(2)为数组中的每个元素赋予其数据类型的默认值。
(3)返回数组对象的引用。
public class Test02 {
public static void main(String[] args) {
static int[] y;
System.out.println(y);
System.out.println(y[0]);
}
}
这段代码编译出错。方法中的变量是局部变量, 只有final修饰符被允许。
public class Test02 {
public static void main(String[] args) {
int[] y;
System.out.println(y);
System.out.println(y[0]);
}
}
这段代码编译出错。变量y没有初始化就被使用。
public class Test02 {
static int[] z;
public static void main(String[] args) {
System.out.println(z);//打印null
System.out.println(z[0]);//抛出空指针异常
}
}
数组变量z作为类的静态变量,没有引用任何数组类型,其默认值为null。
数组变量必须在引用一个数组对象后,才能访问其元素。
public class Test02 {
public static void main(String[] args) {
int[] x = new int[3];
System.out.println(x);//打印[I@de6ced
System.out.println(x[0]);//打印0
}
}
这段代码无误。
7.4数组对象创建后,它的长度是固定的。数组对象的传毒是无法改变,但是数组变量可以改变引用的数组对象。
int[] x = new int[3];
int[] y = x;
x = new int[4];
7.5数组的length属性不能被修改。
7.6当数组的元素为引用类型时,数组中存放的是对象的引用,而不是对象本身。
StringBuffer sb = new StringBuffer(“a”);
StringBuffer[] sbs = new StringBuffer[] {sb,null};
sb.append(“b”);
sb = null;
sbs[0].append(“c”);
System.out.println(sbs[0]);//打印abc
sbs[0] = null;//StringBuffer对象结束生命周期
sbs = null;//StringBuffer数组对象结束生命周期
7.7非法的数组初始化方式
int[] x = new int[5]{1,2,3,4,5}; //不能在[]中指定数组的长度
int[] x;
x={1,2,3,4,5}; //编译出错,{1,2,3,4,5}必须在声明数组变量的语句中使用,不能单独使用。
7.8**数组的创建方式
String[][] ss = new String[3][];
ss[0] = new String[]{“Tom”,”Mike”,”Jack”,null};
ss[1] = new String[]{“Mary”,null,”Linda”};
或
String[][] ss = {
{“Tom”,”Mike”,”Jack”,null},
{“Mary”,null,”Linda”}
};
创建**数组时,必须按照从低维到高维的顺序创建每一维数组。如:
int[][][] b = new int[2][][3];//编译出错
7.9在返回数组的内容为空的场合,返回长度为0的数组比返回null更能简化方法调用者的代码。因为不需要判断返回值是否为null。例:return new char[0];
7.10冒泡排序
7.11二叉查找算法(已排序的数组)
7.12 int[] x = new int[-4];编译通过,但会出现运行时异常,非法数组大小异常。