ArrayList返回NullPointer异常|| Java || OOP

时间:2015-06-13 23:44:56

标签: java arraylist nullpointerexception

嘿,有人可以帮我理解为什么我在尝试运行时仍然会遇到空指针异常? 我只是想学习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();





}
}

2 个答案:

答案 0 :(得分:3)

字段(实例字段或静态字段)被初始化为它们可以容纳的值的“所有位关闭”版本;对象引用,即ar。您的null静态字段以ar.addAddress(...)开头,您永远不会为其分配任何内容。因此,ar会抛出一个NPE,因为nullar = 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();

}