对象的ArrayList没有正确引用每个对象[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

解决方案是从Account类中的变量中删除静态。代码现在按预期工作

我正在尝试创建一个方法来检查数字是否在对象的arraylist中

我最初的想法是这个,但目前不起作用。我的主要课程是这个与相关的代码

private static ArrayList<Account> accounts = new ArrayList<Account>();
public static void main(String[] args) 
{       
    //Creates the three default accounts
    Account ac1 = new Account("account1", 0001, 0);
    Account ac2 = new Account("account2", 0002, 0);
    Account ac3 = new Account("account3", 0003, 0);
    accounts.add(ac1);
    accounts.add(ac2);
    accounts.add(ac3);
}
public static void createAccount()
{
    Boolean doesContain = false;
    String logAccNum = JOptionPane.showInputDialog("please enter your account Number");                 
    int tempAccNum = Integer.parseInt(logAccNum);
    doesContain = checkArray(tempAccNum);       
}
public static boolean checkArray(int checkNum)
{
    for(int i = 0; i <accounts.size(); i++)
    {
            if(accounts.get(i).getMyAccountNum() == checkNum)
            {
                return true;
            }   
    }
    return false;
}

我的帐户类中没有无关代码的代码是

private int myAccountNum;
private int myBalance;
private String myName;

public Account(String name, int accNum, int balance)
{
    this.myName = name;
    this.myAccountNum = accNum;
    this.myBalance = balance;       
}

public int getMyAccountNum()
{
    return myAccountNum;
}

我的代码的当前问题是,如果在createAccount中输入的数字是最后创建的默认帐户,checkArray将仅返回true。我相信Account类中的myAccountNum变量在构造它的最后一个实例后保持不变。

最后,我不想在解决方案中使用迭代器,除非必要,如果你可以使用arrayList和for循环来创建它,那将非常感激

java object arraylist
2个回答
0
投票

属性myAccountNummyBalancemyName必须是NON static,因为这些意味着它们独立于类实例而存在。当你实例化新的Accounts时,它们都将指代相同的变量,而不是拥有自己的变量。

您的代码在所有实例之间说“分享myAccountNummyBalancemyName”。这不是你的意图。


0
投票

原因是因为变量是static.https://beginnersbook.com/2013/05/static-variable/,所有静态变量对于该类的所有对象具有相同的值

© www.soinside.com 2019 - 2024. All rights reserved.