简体   繁体   English

Java中数组的空指针异常

[英]Null Pointer Exception on Array in Java

The following code is returning a NullPointerException in Java.以下代码在 Java 中返回 NullPointerException。 Can anyone clarify my mistake?谁能澄清我的错误?

public void deposit2()
{
    BankAccounts[] accounts2 = new BankAccounts[10];
    accounts2[3].deposit();
}
BankAccounts[] accounts2 = new BankAccounts[10];

is the same as是相同的

BankAccounts[] accounts2 = {null, null, null, ... null };  // (10 times)

You need to assign values to the elements of accounts2 (or, at least to element 3) before you attempt to dereference them.您需要将值分配到的元素accounts2 (或者,至少要件3)试图取消引用它们之前。

Just declare it as you declared it in your code and after that use for loop to assign object reference to all index.只需在代码中声明它,然后使用 for 循环将对象引用分配给所有索引。

For example:例如:

public void deposit2()
{
    BankAccounts[] accounts2 = new BankAccounts[10];
    for(int i=0;i<10;i++)
    {
        accounts2[i] = new BankAccounts();
    }
    accounts2[3].deposite();
}

BankAccounts[] accounts2 = new BankAccounts[10]; creates an object ie an array of bank accounts with 10 references that can point to 10 BankAccount objects,they are initailized to null , you need to create the actual bank objects , try this创建一个对象,即具有 10 个引用的银行帐户数组,可以指向 10 个 BankAccount 对象,它们被初始化为 null ,您需要创建实际的银行对象,试试这个

BankAccounts[] accounts2 = new BankAccounts[10];

for(BankAccounts b:accounts2)//for each loop
{
b=new BankAccounts();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM