嘿,有人可以帮我理解为什么我在尝试运行时仍然会遇到空指针异常? 我只是想学习arraylist,因为我正在学习。
////////////////////////////////////////////
public class Address {
int houseNumber;
String roadNumber;
String areaName;
String cityName;
public Address(int hn, String rn, String an, String cn){
this.houseNumber = hn;
this.roadNumber = rn;
this.areaName = an;
this.cityName = cn;
}
public String toString() {
return "House # " + this.houseNumber + "\nRoad # " + this.roadNumber + "\n" + this.areaName + "\n" + this.cityName;
}
}
/////////////////////////////////////////////// //
import java.util.ArrayList;
public class AddressReferences {
ArrayList<Address> myCollection = new ArrayList<Address>();
public void addAddress (int hn, String rn, String an, String cn) {
myCollection.add(new Address(hn,rn,an,cn));
}
public void printAddress () {
for ( Address i : myCollection){
System.out.println (i);
}
}
}
//////////////////////////////////////
public class Test {
static AddressReferences ar;
public static void main(String[] args){
ar.addAddress(46, "9/a", "Kotol", "Dhaka");
ar.addAddress(44, "9/a", "Kotol", "Dhaka");
ar.addAddress(28, "9/a", "Kotol", "Dhaka");
ar.addAddress(89, "12/a", "Kotol", "Dhaka");
ar.addAddress(60, "7/a", "Kotol", "Dhaka");
ar.printAddress();
}
}
答案 0 :(得分:3)
字段(实例字段或静态字段)被初始化为它们可以容纳的值的“所有位关闭”版本;对象引用,即ar
。您的null
静态字段以ar.addAddress(...)
开头,您永远不会为其分配任何内容。因此,ar
会抛出一个NPE,因为null
是ar = new AddressReferences();
。
要解决此问题,请添加
main
...在ar
使用{{1}}之前{{1}}。
答案 1 :(得分:0)
此处,零点异常并不意味着myCollection
为空,这意味着ar
为空,因此将ar = new AddressReferences();
添加到主函数中。
public static void main(String[] args){
ar = new AddressReferences();
ar.addAddress(46, "9/a", "Kotol", "Dhaka");
ar.addAddress(44, "9/a", "Kotol", "Dhaka");
ar.addAddress(28, "9/a", "Kotol", "Dhaka");
ar.addAddress(89, "12/a", "Kotol", "Dhaka");
ar.addAddress(60, "7/a", "Kotol", "Dhaka");
ar.printAddress();
}