为什么我不能将一个元素添加到另一个类的列表中?

时间:2014-12-01 19:56:55

标签: java arrays list class

我有两个班级,PizzaPizzaTopping。在PizzaArrayList应该存储字符串(披萨顶部)。我正在尝试从ham类中的PizzaTopping方法向数组添加元素。但是,当我打印列表时,它显示为空。为什么呢?

这是PizzaTopping:

public class PizzaTopping {

    Pizza p = new Pizza();

    public void ham() {
        double cost = 1;
        System.out.println("im in ham");
        p.addToPizza("ham");
        p.setCost(p.getCost() + cost);
    }
}

这是我的Pizza课程:

import java.util.ArrayList;
import java.util.Arrays;

public class Pizza {

    private double cost;
    ArrayList<String> pizza = new ArrayList<String>();

    public double getCost() {
        return cost;
    }

    public void setCost(double cost) {
        this.cost = cost;
    }

    public void addToPizza(String x) {
        System.out.println("im in add");
        pizza.add(x);
    }

    public static void main(String [] args) {
        //scanner to add topping
        PizzaTopping pt = new PizzaTopping();
        Pizza p = new Pizza();
        pt.ham();
        System.out.println(Arrays.toString(p.pizza.toArray()));
    }

}

2 个答案:

答案 0 :(得分:2)

只需这样做:

PizzaTopping pt = new PizzaTopping();
pt.ham();
System.out.println(Arrays.toString(pt.p.pizza.toArray()));

问题是你在main中创建了一个新的pizza对象而没有使用绑定到pt的那个对象,所以ham方法是在pt.p中保存值而不是p(你在main方法中创建的)

答案 1 :(得分:0)

你的Pizza类应该有一个默认的或无参数的构造函数来制作一个芝士披萨(有一些酱)。它应该提供.addTopping(PizzaTopping topping) to allow adding topping to it. In theory, there should be an unlimited number of topping that you can add. However, to control the number of toppings, you can probably limit them by adding them to an array (or some Collections`对象)。

public class Pizza
{
    private List<PizzaTopping> toppings = new ArrayList<PizzaTopping>();

    public Pizza() {} // constructs basic cheese pizza

    public void addTopping(PizzaTopping topping) throws IllegalArgumentException
    {
        if (toppings == null)
            throw new IllegalArgumentException("Topping cannot be null");
        toppings.add(new PizzaTopping(topping.toString());
    }

    @Override
    public String toString()
    {
        return "Pizza with " + toppings.size() + " toppings: " + toppings.toString();
    }
}

PizzaTopping类应该有一个单参数构造函数(String)来提供顶部的名称。

public PizzaTopping
{
    private String name;

    public PizzaTopping(String name) throws IllegalArgumentException
    {
        if (name == null)
            throw new IllegalArgumentException("Name cannot be null");
        this.name = name;
    }

    @Override
    public String toString()
    {
        return name;
    }
}

您的测试类应该只是创建浇头,比萨饼,并将比萨添加到比萨饼中。每个类都有一个方便的方法(toString())来打印出有关该对象的信息。浇头打印出它的名字,比萨饼打印出浇头的数量和浇头是什么。 (这是未经测试的代码但应该有效。)

将新的PizzaTopping实例添加到比萨饼的原因是因为不应在不同的Pizza实例之间共享浇头。此外,如果不允许空对象,则应确保检查空对象。为空对象抛出IllegalArgumentException是一种很好的方式,这些非法参数不会使它(或中断)进入你的代码。