Java - 将一个对象添加到数组列表,然后将另一个对象添加到数组列表会导致第一个元素被覆盖

发布于 2024-10-07 11:36:27 字数 3830 浏览 6 评论 0原文

我目前正在做我的第三年编程项目,它是一个作品集跟踪器。 :/ 我已经创建了 Stock_API 和 Portfolio_API 接口(及其实现)和一个 GUI 类,该类在实例化时采用两个参数,如下所示:

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

我使用此构造函数作为将这些接口的实现获取到 GUI 中的一种方式,而不会将实现暴露给GUI(这是该项目的主要目标之一)。投资组合对象有一个名称(字符串)和一个 ArrayList。股票对象具有股票代码(字符串)、股票名称(字符串)、股票价值(浮点数)、股票数量(整数)和持有价值(浮点数)。

在 GUI 中,我有一个 portCollection 数组列表,其中保存有 Portfolio_API 类型的对象,这样系统就可以跟踪多个投资组合。另外,正如上面的代码块中提到的,有一个 tempStock 和 tempPort 对象。

很抱歉向您提供有关该计划的如此多的详细信息,但我认为最好这样我才能了解上下文。无论如何,眼前的问题。我有一种方法,使用 GUI 获取股票代码、股票名称和股票数量,并将股票添加到当前打开的投资组合中(每个投资组合都有自己的选项卡)。该方法如下所示:

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

当我添加不止一种股票时,新股票将取代旧股票并有效地覆盖它。我认为这是对 tempStock 的重用。不知道为什么,但如果我将变量添加到数组列表中,它就会成为该数组列表的一部分,并且不需要与 tempStock 变量关联?

与提到的数组列表一起使用的方法:

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

这两个位于 Portfolio 类中:

@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'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 the 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岛歌少女 2024-10-14 11:36:27

是的,当您说您认为这是因为您重用了 tempStock 变量时,我认为您是对的。该变量仍然引用原始对象,因此在 tempStock 上调用 setTicker() 等也会更改 ArrayList 引用的对象,因为它是同一个对象。尝试重新初始化您的 tempStock 并查看是否有影响:

// 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);

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);
子栖 2024-10-14 11:36:27

感谢大家的意见。 @oracle 认证教授在为 addStock 添加重载方法后帮助解决了股票问题,但结果发现同样的问题也困扰着投资组合。

我所做的是在 Portfolio_API 中创建一个 makePortfolio 方法来创建一个新的投资组合并将其返回。这样就可以避免任何令人讨厌的覆盖,现在也将其添加到库存中。

再次感谢你们。晚安! :)

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! :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文