开发者

Java - Add an object to an arraylist, then adding another to the arraylist causes the first element to be overwritten

开发者 https://www.devze.com 2023-01-30 16:28 出处:网络
I\'m currently doing my third year programming project and its a folio tracker. :/ I have crated Stock_API and Portfolio_API interfaces (and implementations of them) and a GUI class which when instant

I'm currently doing my third year programming project and its a folio tracker. :/ I have crated Stock_API and Portfolio_API interfaces (and implementations of them) and a GUI class which when instantiated takes two parameters as so:

public GUI(Portfolio_API p, Stock s){
      tempPort = p;
      tempStock = s;
}

I use this constructor as a way of getting implementations of these interfaces into th开发者_开发问答e GUI without exposing the implementation to the GUI (which is one of the main objectives of this project). A portfolio object has a name(string) and an ArrayList. A stock object has a ticker symbol(string), a stock name(string), a share value(float), a number of shares(int) and a value of holding(float).

In the GUI i have a portCollection array list which holds objects of type portfolio_API and this is so the system can keep track of multiple portfolios. Also as mentioned in the block of code above has a tempStock and tempPort object.

Sorry to give u so much detail about the program but i thought it best so i could get the context across. Anyway, the problem at hand. I have a method which uses the GUI to get a ticker symbol, a stock name and a number of shares and adds the stock to the current portfolio open(each portfolio has its own tab). The method looks like this:

public void addStock() {
    int num_shares = 0;
    float dailyChange = 0.0f;
    float stockValue = 0.0f;
    boolean succeed = true;

    // GUI gets information of stock from user
    String ticker = JOptionPane.showInputDialog(frame,
            "Enter the ticker symbol:");
    String stockName = JOptionPane.showInputDialog(frame,
            "Enter the Stock name:");
    try {
        num_shares = Integer.parseInt(JOptionPane.showInputDialog(frame,
                "Enter the number of shares:"));
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(frame,
                "Number of shares was not an integer. Try again");
        succeed = false;
    }

    // If parsing was successful...
    if (succeed) {
        tempStock.setTicker(ticker);
        tempStock.setNumberOfShares(num_shares);
        tempStock.setStockName(stockName);

        // Fetches newest value using the current ticker symbol
        boolean succeedUpdate = tempStock.updateShareValue();

        if (succeedUpdate) {
            tempStock.calculateValueOfHolding();

            // Adds to the current portfolio...
            String tabName = tabbedPane.getTitleAt(tabbedPane
                    .getSelectedIndex());
            System.out.println(tabName);
            findPortfolio(tabName).addStock(tempStock);
            findPortfolio(tabName).sort();

            // ...Then adds it to the table
            JPanel j = (JPanel) tabbedPane.getSelectedComponent()
                    .getComponentAt(0, 0);
            JViewport v = ((JScrollPane)   j.getComponent(0)).getViewport();
            JTable table = (JTable) v.getComponent(0);

            float currentTotal = findPortfolio(tabName).getTotal();

            // Updates the total label
            ((JLabel) j.getComponent(1)).setText("Total: " + currentTotal);

            Object[] newStock = { tempStock.getTicker(),
                    tempStock.getStockName(),
                    tempStock.getNumberOfShares(),
                    tempStock.getShareValue(),
                    tempStock.getValueOfHolding() };
            ((DefaultTableModel) table.getModel()).addRow(newStock);
        }
    }
}

When I add more than one stock, the new stock takes place of the old one an effectively overwrites it. I think its the reuse of tempStock that is doing it. Not sure why though as surely if i add the variable to an arraylist it becomes part of that arraylist and needs no association with the tempStock variable?

Methods that are used with the mentioned arraylists :

private Portfolio_API findPortfolio(String name) {
        Portfolio_API p = null;
        for (int i = 0; i < portCollection.size(); i++) {
            if (portCollection.get(i).getName() == name) {
                p = portCollection.get(i);
            }
        }

These two are in the Portfolio class:

@Override
public boolean addStock(Stock_API s) {
    if (!doesExist(s)) {
        portfolio.add(s);
        return true;
    } else {
        return false;
    }

}

@Override
public boolean doesExist(Stock_API s) {
    boolean found = false;
    for (int i = 0; i < portfolio.size(); i++) {
        if (portfolio.get(i).getTicker() == s.getTicker()) {
            found = true;
        }
    }
    return found;
}

I've only come here for help because i have hit a brick wall and I really need help. If anyone could give me any suggestions, i'd be eternally in your debt.

Thanks, Chris


Yes, I think you are right when you say you think it's because you're reusing the tempStock variable. This variable still references the original object so calling setTicker() etc on tempStock also changes the object referenced by your ArrayList because it's the same object. Try reinitialising your tempStock and see if it makes a difference:

// If parsing was successful...
    if (succeed) {
        tempStock = new Stock(); // or however you instantiate this object
        tempStock.setTicker(ticker);
        tempStock.setNumberOfShares(num_shares);
        tempStock.setStockName(stockName);


Thanks guys for all your input. @oracle certified professor helped with the stock problems after adding an overloaded method for addStock but turned out the same problems plagued portfolio.

What I did was create a makePortfolio method in Portfolio_API to create a new portfolio and return it. That way it avoids any nasty overwrite, gonna add it to stock too just now.

Thanks again guys. Good night! :)

0

精彩评论

暂无评论...
验证码 换一张
取 消