在Java中Assinging和Object to Array,它返回null

1 java

我创建了一个程序并将客户对象分配给customers数组,但是当我尝试在数组中获取对象时,它返回null.我是Java的新手,请帮助我解决我的错误.

public class Customer {

    private String firstname,lastname;

    public Customer(String f,String l){
        this.firstname = f;
        this.lastname = l;
    }

    public String getFirstName(){
        return firstname;
    }

    public String getLastName(){
        return lastname;
    }   
}

public class Bank {

    private Customer [] customers;
    private int numberofCustomers;

    public Bank(){
        customers = new Customer [5];
        numberofCustomers = 0;

    }

    public void addCustomer(String f,String l){
        int i = numberofCustomers++;
        customers[i] = new Customer(f,l);
    }

    public int getNumberofCustomer(){
        return numberofCustomers;
    }

    public Customer getCustomerMethod(int index){
        return customers[index];
    }
}

public class TestAccount {

public static void main (String [] args){

        Bank b = new Bank();
        b.addCustomer("Test", "LastName");
        System.out.print(b.getNumberofCustomer());
        System.out.print(b.getCustomerMethod(1));

    }
}
Run Code Online (Sandbox Code Playgroud)

Per*_*ror 5

数组索引从零开始.您已在数组中的索引0第一个元素处添加了一个客户,您应该使用相同的索引来获取该元素.目前索引1没有任何内容,因此您的代码返回null;

System.out.print(b.getCustomerMethod(0));
Run Code Online (Sandbox Code Playgroud)

假设数组大小为5,因此其索引将为0,1,2,3,4,其中0是第一个索引,4是最后一个索引.

在此行之后,b.addCustomer("Test", "LastName");您的数组将是:

Array: [Customer("Test", "LastName") , null , null, null, null]
Index:                0             ,  1   ,  2  ,   3 ,  4
Run Code Online (Sandbox Code Playgroud)

当你尝试'System.out.print(b.getCustomerMethod(1));' 它返回null.正如您所看到的,您的数组在索引1处为null.