数组的初始化
数组定义与为数组元素分配空间和赋值的操作分开进行
动态初始化
例如:
public class Test {
public static void main(String[] args) {
int a[];
a = new int[3];
a[0] = 3 ; a[1] = 9 ; a[2] = 8 ;
Date days [];
days = new Date[3];
days[0] = new Date(1,12,2012);
days[1] = new Date(2,12,2012);
days[2] = new Date(3,12,2012);
}
}
class Date {
int year; int month; int day;
Date(int y ,int m , int d) {
year = y;
month = m;
day = d;
}
}
静态初始化:
在定义数组的同时就为数组元素分配空间并赋值
例如:
public class Test {
public static void main(String[] args) {
int a[] = {1 , 3 , 5};
Date days[] = {
new Date(1,12,2012),
new Date(2,12,2012),
new Date(3,12,2012)
};
}
}
class Date {
int year,month,day;
Date(int y, int m , int d) {
year = y;
month = m;
day = d;
}
}
数组是引用类型,它的元素相当于类的成员变量,因此数组分配空间后,每个元素也被按照成员变量的规则被隐式初始化
例如:
public class Test {
public static void main(String[] args) {
int a[] = new int[5];
Date[] days = new Date[3];
System.out.println(a[3]);
System.out.println(days[2]);
}
}
class Date {
int year,month,days;
Date(int y,int m,int d){
year = y;
month = m;
days = d;
}
}