对象数组的初始化方式
动态初始化:类名称 对象数组名称 [] = new 类名称[长度];
静态初始化:类名称 对象数组名称 [] = new 类名称[]{实例化对象, 实例化对象, ...};
首先,定义简单Person类
class Person{
String name;
int age;
public Person(String n,int a){
name = n;
age = a;
}
public String getInfo(){
return "姓名:"+name+",年龄:"+age;
}
}
其次,初始化对象数组
范例1:动态初始化
public class Carr{
public static void main(String args[]){
Person per[] = new Person[3];
per[0] = new Person("张三",10);
per[1] = new Person("李四",20);
per[2] = new Person("王五",30);
for(int i =0;i<per.length;i++){
System.out.println(per[i].getInfo());
}
}
}
范例2:静态初始化
//静态初始化方式1
public class Carr{
public static void main(String args[]){
Person perA = new Person("张三",10);
Person perB = new Person("李四",20);
Person perC = new Person("王五",30);
Person per[] = new Person[]{perA, perB, perC};
for(int i =0;i<per.length;i++){
System.out.println(per[i].getInfo());
}
}
}
//静态初始化方式2
public class Carr{
public static void main(String args[]){
Person per[] = new Person[]{new Person("张三",10), new Person("李四",20), new Person("王五",30)};
for(int i =0;i<per.length;i++){
System.out.println(per[i].getInfo());
}
}
}
以上代码的内存关系图描述如下: