1 简介
- 若初始化不到位,常遇到“空指针异常”(java.lang.NullPointerException)的问题。
- 此类解决方案是:在声明自定义类数组后,必须再对每一个数组元素 (自定义类)进行实例化。
--
2 代码示例
此处,自定义类为Fruit;类数组名为f,数组元素个数为3;
2.1 类数组的声明形式(4种常见形式):
Fruit[] f = new Fruit[3];
Fruit f[] = new Fruit[3];
Fruit f[];
f = new Fruit[3];
Fruit[] f;
f = new Fruit[3];
2.2 对该自定义类数组的每个元素进行实例化(2种常见形式):
for(int i=0; i<f.length;i++)
{ f[i] = new Fruit();}
for(Fruit r : f)
{r = new Fruit();}
2.3 完整源代码
import java.io.*;
import java.util.*;
public class custom_array_initial {
public static void main(String[] args) throws IOException{
Fruit[] f = new Fruit[3];
f[0] = new Fruit();
f[0].setName("Apple");
f[0].setPrice(9.9);
f[1] = new Fruit();
f[1].setName("Orange");
f[1].setPrice(12.5);
f[2] = new Fruit("Banana", 15.9);
System.out.println(">>>>>> Print result: ");
for(Fruit r : f){
System.out.println("Name: " + r.name + ", Price: " + r.price);
}
}
public static class Fruit{
String name;
double price;
public Fruit(){
}
public Fruit(String name, double price) {
this.name = name;
this.price = price;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return this.price;
}
}
}
3 输出结果
输出结果为:
|