接受对象数组的类然后添加到ArrayList

时间:2018-12-06 02:31:17

标签: java arrays object arraylist

所以下面我有一个Dog类和Doghouse类。我对Java还是很陌生,所以还不清楚如何创建一个Doghouse类,该类具有一个接受Dogs数组并将其添加到ArrayList的构造函数。我下面的代码有意义吗?

 public class Dog{
   public Dog(int number, double price, double sWeight, String origin, String webpage){
   }
}



import java.util.ArrayList;

public class Doghouse{
private ArrayList<Dog> dogList;

public Doghouse(Dog[] newDog){

    for(int i = 0; i < newDog.length; i++){
        dogList.add(newDog[i]);
    }

}

}

1 个答案:

答案 0 :(得分:2)

当前使用dogList而不进行初始化会抛出NPE。

您可以将其修复为:

public static class Doghouse {
    private List<Dog> dogList;

    public Doghouse(Dog[] newDog) { // constructor name corrected
        this.dogList = Arrays.stream(newDog).collect(toList());
    }
}

或者可能更容易理解

public Doghouse(Dog[] newDog) {
    this.dogList = new ArrayList<>(); // initialise first
    dogList.addAll(Arrays.asList(newDog)); // add later
}