ArrayList.add:它是如何工作的?

时间:2017-04-29 11:18:28

标签: java eclipse arraylist

我创建了这个小程序..

public static void main(String[] args) {
    Person P = new Person("will", "Deverson", "15/06/1987", "Bonifico");
    Product PC = new Product("Asus VivoBook", "AVB2562", 799.99);
    Product ROUTER = new Product("TP-Link X3", "X3-201", 142.99);
    Product ADAPTER = new Product("Aukey Type-C Adapter", "C-778", 11.20);

    ArrayList<Product> listProduct = new ArrayList<Product>();
    listProduct.add(PC);
    listProduct.add(ROUTER);
    listProduct.add(ADAPTER);

    //numero elementi nella lista prodotti
    int nProducts = listProduct.size();
    System.out.println("Il tuo carrello contiene " +nProducts +" elementi: ");
    for (Product p : listProduct)
        System.out.println("> name: " +p.getName() +"   model: " +p.getModel() +"   cost: " +p.getCost() +"€.\n");

    //calcolo del totale
    double total = 0;
    for (Product p : listProduct){
        total = total + p.getCost();;
    }

当我执行时我有这个输出:

Il tuo carrello contiene 3 elementi: 
> name: C-778   model: C-778    cost: 11.2€.

> name: C-778   model: C-778    cost: 11.2€.

> name: C-778   model: C-778    cost: 11.2€.

为什么他还会在名称字段中打印id模型?为什么我有3次相同的物体?

这是&#34;产品&#34;上课你要我发帖:)我认为这是正确的,我唯一的疑问是关于使用&#34;这个&#34;在变量宣言中。

public class Product {
    static String name;
    static String model;
    static double cost;

    public Product(String n, String m, double d) {
        name = m;
        model = m;
        cost = d;
    }

    public String getName(){
        return name;
    }

    public String getModel(){
        return model;
    }

    public double getCost(){
        return cost;
    }
}

1 个答案:

答案 0 :(得分:1)

您的“产品”类中存在问题。

试试这个:

public class Product {

    private String name, model;
    private Double price;

    public Product(String name, String model, Double price) {
        this.name = name;
        this.model = model;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public String getModel() {
        return model;
    }

    public Double getCost() {
        return price;
    }
}

“Main”类看起来没问题。

输出:

Il tuo carrello contiene 3 elementi: 

> name: Asus VivoBook   model: AVB2562   cost: 799.99€.

> name: TP-Link X3   model: X3-201   cost: 142.99€.

> name: Aukey Type-C Adapter   model: C-778   cost: 11.2€.

你可以改变这个:total = total + p.getCost();到这个:total+=p.getCost();这和你写的一样,但更干净: - ]