将对象添加到Arraylist会导致nullpointerexception

时间:2019-06-06 11:17:19

标签: java arraylist nullpointerexception

我无法向Arraylist中添加任何(或可能只是第一个?)对象

Bikestore是一个对象,其中包含所有自行车的名称和Arraylist

自行车具有3种不同的属性(2个字符串,1个双精度)

通过“ addbiketocollection()”方法将自行车添加到商店中,在此方法中,我使用.add函数。

 public class Bikes 
    String brand ;
String color;
double price;

Bike(String brand, String color, double price){
    this.brand = brand;
    this.color = color;
    this.price = price;
}

public class Bikestore {

String name;
ArrayList<Bike> Collection = new ArrayList<>();

Bikestore (String name, ArrayList<Bike> Collection){
    this.name = name;
    this.Collection = Collection;
}


public void AddBikeToCollection (Bike NewBike) {
    Collection.add(NewBike);


}

  Mainclass
    Bike Bike1 = new Bike ("Cube", "Black", 400);

    Bikestore SellingBikes = new Bikestore ("SellingBikes", null);

    SellingBikes.AddBikeToCollection(Bike1);

}

当我尝试将自行车添加到Bikestore时,我得到一个nullpointerxception 线程“主”中的异常java.lang.NullPointerException

我已经用谷歌搜索了问题,并观看了一些视频,但是这些视频都没有包含对象的数组列表。

3 个答案:

答案 0 :(得分:0)

问题在Mainclass中,您正在为Bikestore构造函数的集合传递null

  

Bikestore SellingBikes =新的Bikestore(“ SellingBikes”,空);

要么传递Bike对象的ArrayList,要么完全删除该参数。由于您要在BikeStore类中初始化arrayList,所以传递另一个数组是多余的

public class Bikestore {

    String name;
    ArrayList<Bike> collection;

    Bikestore (String name){
         this.name = name;
         this.Collection = new ArrayList<>();
    }
}

答案 1 :(得分:0)

您的问题是这行代码

Bikestore SellingBikes = new Bikestore ("SellingBikes", null);

在构造函数中,将Bike列表设置为null,因此即使将Bike列表初始化为新的ArrayList <>(),也没关系

要解决此问题,您应该先创建自行车列表,然后传递到Bikestore对象

ArrayList<Bike> bikes = new ArrayList<>(); 
Bikestore SellingBikes = new Bikestore ("SellingBikes", bikes);

或者简单:


public void AddBikeToCollection (Bike NewBike) {
if(list == null) {
    list = new ArrayList<>(); 
}
    list.add(NewBike);
}

无论如何都不要将名称声明为保留关键字:Collection

答案 2 :(得分:0)

似乎在创建BikeStore时,您传入的是null而不是ArrayList。因此,您可以将行更改为:

 Bikestore SellingBikes = new Bikestore ("SellingBikes", this.Collection);

或者在BikeStore构造函数中使其变得

Bikestore (String name){
    this.name = name;
}

以及创建自行车商店时的Bikestore SellingBikes = new Bikestore ("SellingBikes");