Java 将对象添加到Arraylist会导致nullpointerexception

Java 将对象添加到Arraylist会导致nullpointerexception,java,arraylist,nullpointerexception,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

我不能添加任何内容,或者可能只是第一个?对象到我的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时,我得到一个NullPointerException 线程主java.lang.NullPointerException中出现异常


我已经用谷歌搜索了我的问题并观看了一些视频,但这些视频中没有一个包含带有对象的arraylist。

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

Bikestore SellingBikes=新Bikestore SellingBikes,空

传递Bike对象的ArrayList或完全删除该参数。由于您正在初始化BikeStore类中的arrayList,因此传递另一个是redundent

public class Bikestore {

    String name;
    ArrayList<Bike> collection;

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

您的问题是这行代码

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

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

 Bikestore SellingBikes = new Bikestore ("SellingBikes", this.Collection);
或者在BikeStore构造函数中

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

以及创建自行车商店时的提示:Bikestore SellingBikes=新的Bikestore SellingBikes

注意java命名约定。变量和方法名称应以小写字符New Bikestore SellingBikes开头,null;我将应用您的命名约定,我实际上不这样编程,但我认为通过@AxelH查看会更容易,我该怎么做?如何通过arraylist?ArrayList集合[];Bikestore SellingBikes=新Bikestore SellingBikes,ArrayList集合;这不起作用。我如何创建Arraylist为空的对象而不使用null关键字?Bikestore是一个包含名称和Arraylist的对象-不,它不包含任何Arraylist,因为在您的代码中,没有创建任何Arraylist缺少新的Arraylist第二个解决方案,这在这一点上是无用的:this.Collection=Collection;是的,你的权利。福戈特想摆脱那条线。我刚刚把它删掉了。谢谢