【问题标题】:A class that accepts an array of objects then adds to an ArrayList接受对象数组的类然后添加到 ArrayList
【发布时间】:2018-12-06 02:31:16
【问题描述】:

所以下面我有一个 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]);
    }

}

}

【问题讨论】:

  • 由于缺乏研究,我投票决定将此问题作为题外话结束
  • 它会很高兴地向你扔一个NullPointerException
  • 还有public Warehouse和狗窝有什么关系?
  • 小错字。编辑以适应。感谢您的反馈

标签: java arrays object arraylist


【解决方案1】:

目前使用 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
}

【讨论】:

    猜你喜欢
    • 2020-11-08
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多