comscis
comscis

Reputation: 123

Having trouble with the arraylist get method

Basically, I have an ArrayList of BudgetItem objects (BudgetItem being a class I made). Each BudgetItem has three instance variables, price, name, and quantity with setters and getters for each. I am adding each BudgetItem to the ArrayList one at a time, each with different information in the price variable. When I go to print out any price element of the ArrayList, using the get method, the console will always print the last price that was entered. Below, I will paste some sample code to help:

public class Register {
    private ArrayList<BudgetItem> register = new ArrayList<BudgetItem>();
    public Register(double[] price) {
        //Creates a register ArrayList with specified number of
        //elements and populates it with BudgetItems that contain
        //the data in the price array entered in the declaration.

        BudgetItem bi = new BudgetItem();

        for(int i = 0; i<price.length; i++) {
                bi.setPrice(price[i]);
        register.add(bi);
                if(i=0) {                //This if statement is for debugging.
                    System.out.println(register.get(i).getPrice());
                }
        }
            //This is also for debugging.
            double i = register.get(0).getPrice();
    System.out.println(i);
    }
}

Through my debugging efforts I found that the problem is with the get method in ArrayList. No matter what I do it returns the last instance of price that was entered. My question is why won't the get method return the specified element?

Upvotes: 1

Views: 118

Answers (3)

BSS
BSS

Reputation: 76

Add BudgetItem bi = new BudgetItem(); inside for loop

Upvotes: 2

Alexis C.
Alexis C.

Reputation: 93842

Well the problem is that you always modify the same BudgetItem object.

Try :

    for(int i = 0; i<price.length; i++) {
            BudgetItem bi = new BudgetItem(); <-- move it inside the for loop
            bi.setPrice(price[i]);
            register.add(bi);
    }

Upvotes: 2

Vidya
Vidya

Reputation: 30310

You are only adding a single BudgetItem and setting and resetting its price. You need to add new BudgetItems and set their prices accordingly.

Upvotes: 2

Related Questions