Stefano
Stefano

Reputation: 45

ArrayList.add: how does it work?

I create this little program..

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();;
    }

and when i execute i have this output:

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€.

Why does he print id model also in the name field? And why do I have the same object 3 times?

Here's the "Product" class you asked me to post :) I think it is correct, my only doubt is about using "this" in the declaration of the variabiles.

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;
    }
}

Upvotes: 0

Views: 97

Answers (1)

Ion
Ion

Reputation: 371

Looks that you have a problem in your "Product" class.

Try this:

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;
    }
}

The "Main" class looks OK.

And the output:

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€.

And you can change this: total = total + p.getCost(); to this: total += p.getCost(); which is the same thing as what you wrote, but more clean :-]

Upvotes: 1

Related Questions