将元素存储到数组中但在 Java 之后更新数组索引

Storing element into array but having array index update after in Java

我是 java 的新手,所以我只是在练习我学到的一些东西,并一直在尝试制作一个存储客户账户等的银行程序。这是最开始的地方我有一个名为 "accounts" 的 Customer 类型的数组,它是我创建的 class,它在用户名、密码和帐号中包含 3 个参数。

我想让那个数组以这种方式存储所有客户,正如您从方法 "addAcc" 中看到的那样。在这里,我将新客户对象作为第一个元素添加到客户类型数组中,但我不确定如何在 NEXT 数组索引处添加下一个客户,当我下次调用此方法添加另一个时如何更新索引用户?或者有其他方法可以解决这个问题吗?

public class Bank {
        private double interest_rate = 1.01; // interest rate 
        private Customer[] accounts = new Customer[1000]; // array to store accounts

    // adds new customer 
    public void addAcc (String user, String pass, int accNum) {
        Customer accID = new Customer(user,pass,accNum);
        this.accounts[0] = accID; 
    }

只需创建一个计数器变量,它将跟踪已添加了多少客户

public class Bank {
    private double interest_rate = 1.01; // interest rate 
    private Customer[] accounts = new Customer[1000]; // array to store accounts
    private int counter=0;

// adds new customer 
public void addAcc (String user, String pass, int accNum) {
    Customer accID = new Customer(user,pass,accNum);
    this.accounts[counter++] = accID; 
}

更好的解决方案是使用 ArrayList:

public class Bank {
    private double interest_rate = 1.01;
    private List<Customer> accounts = new ArrayList<>();

    public void addAcc (String user, String pass, int accNum) {
        Customer accID = new Customer(user, pass, accNum);
        this.accounts.add(accID); 
    }
}

此解决方案也更安全,因为数组列表会根据需要动态调整自身大小。对于第一个使用数组的解决方案,当达到数组的容量时会出现错误。

郑重声明,作为较差的替代方案,您可以记一个数:

public class Bank {
    private double interest_rate = 1.01; // interest rate 
    private Customer[] accounts = new Customer[1000]; // array to store accounts
    private lastIndex = -1;

    // adds new customer 
    public void addAcc (String user, String pass, int accNum) {
        Customer accID = new Customer(user,pass,accNum);
        this.accounts[++lastIndex] = accID; 
    }
}

最好使用集合而不是数组。可能是一个 ArrayList 但是,如果您仍然喜欢使用数组并继续,那么您必须检查下一个数组元素是 null 并将新对象添加到其中。为此,您可以每次都遍历数组,或者有一个索引并在添加帐户时更新该索引

例如

public class Bank {
        private static nextIndex = 0;
        private double interest_rate = 1.01; // interest rate 
        private Customer[] accounts = new Customer[1000]; // array to store accounts

    // adds new customer 
    public void addAcc (String user, String pass, int accNum) {
        Customer accID = new Customer(user,pass,accNum);
        this.accounts[nextIndex++] = accID; 
    }