Java 创建对象数组时出现 NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1922677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:28:35  来源:igfitidea点击:

NullPointerException when Creating an Array of objects

javaarraysnullpointerexception

提问by marjasin

I have been trying to create an array of a class containing two values, but when I try to apply a value to the array I get a NullPointerException.

我一直在尝试创建一个包含两个值的类的数组,但是当我尝试将一个值应用于该数组时,我得到了一个 NullPointerException。

public class ResultList {
    public String name;
    public Object value;
}

public class Test {
    public static void main(String[] args){
        ResultList[] boll = new ResultList[5];
        boll[0].name = "iiii";
    }
}

Why am I getting this exception and how can I fix it?

为什么我会收到此异常以及如何修复它?

采纳答案by Nathan Hughes

You created the array but didn't put anything in it, so you have an array that contains 5 elements, all of which are null. You could add

您创建了数组但没有在其中放置任何内容,因此您有一个包含 5 个元素的数组,所有元素均为空。你可以添加

boll[0] = new ResultList();

before the line where you set boll[0].name.

在您设置 boll[0].name 的行之前。

回答by ufukgun

I think by calling

我认为通过调用

ResultList[] boll = new ResultList[5];

you created an array which can hold 5 ResultList, but you have to initialize boll[0]before you can set a value.

您创建了一个可以容纳 5 个 ResultList 的数组,但必须先进行初始化,boll[0]然后才能设置值。

boll[0] = new ResultList();

回答by chburd

ResultList[] boll = new ResultList[5];

creates an array of size=5, but does not create the array elements.

创建大小为 5 的数组,但不创建数组元素。

You have to instantiate each element.

您必须实例化每个元素。

for(int i=0; i< boll.length;i++)
    boll[i] = new ResultList();

回答by Rishikesh Dhokare

As many have said in the previous answers, ResultList[] boll = new ResultList[5];simply creates an array of ResultList having size 5 where all elements are null. When you are using boll[0].name, you are trying to do something like null.nameand that is the cause of the NullPointerException. Use the following code:

正如许多人在前面的答案中所说的那样,ResultList[] boll = new ResultList[5];只需创建一个大小为 5 的 ResultList 数组,其中所有元素都为空。当您使用 时boll[0].name,您正在尝试执行类似的操作null.name,这就是 NullPointerException 的原因。使用以下代码:

public class Test {
    public static void main(String[] args){
        ResultList[] boll = new ResultList[5];

        for (int i = 0; i < boll.length; i++) {
            boll[i] = new ResultList();
        }

        boll[0].name = "iiii";
   } 
}

Here the for loop basically initializes every element in the array with a ResultListobject, and once the for loop is complete, you can use

这里 for 循环基本上是用一个ResultList对象初始化数组中的每个元素,一旦 for 循环完成,就可以使用

boll[0].name = "iiii";

回答by spazBarnum

Furthermore, you can prove this to yourself by adding a debug line to your class, such as:

此外,您可以通过在类中添加调试行来向自己证明这一点,例如:

public class ResultList {
    public String name;
    public Object value;

    public ResultList() {
        System.out.println("Creating Class ResultList");
    }
}

Whenever an object is created, one of its constructors must be called (if there is no constructor, a default one is created automatically, similar to the one you already have in your class). If you only have one constructor, then the only way to create an object is to call that constructor. If the line

无论何时创建对象,都必须调用其构造函数之一(如果没有构造函数,则会自动创建一个默认构造函数,类似于您在类中已有的构造函数)。如果您只有一个构造函数,那么创建对象的唯一方法就是调用该构造函数。如果线

ResultList[] boll = new ResultList[5]; 

really created 5 new objects, you would see your debug line appear on the console 5 times. If it does not, you know the constructor is not being called. Notice also that the above line does not have a parameter list with open and close parentheses "()" so it is not a function call - or constructor call. Instead, we are only referring to the type. We are saying: "I need space for an array of ResultList objects, up to 5 total." After this line, all you have is empty space, not objects.

真正创建了 5 个新对象,您会看到您的调试行出现在控制台上 5 次。如果没有,您就知道没有调用构造函数。另请注意,上面的行没有带有左括号和右括号“()”的参数列表,因此它不是函数调用 - 或构造函数调用。相反,我们仅指类型。我们在说:“我需要一个 ResultList 对象数组的空间,总共最多 5 个。” 在这一行之后,您所拥有的只是空白空间,而不是对象。

As you try out various fixes, the debug line will help confirm you are getting what you want.

当您尝试各种修复时,调试行将帮助确认您得到了想要的东西。

回答by Usama Tahir

ResultList p[] = new ResultList[2];

By writing this you just allocate space for a array of 2 elements. You should initialize the reference variable by doing this:

通过编写此代码,您只需为包含 2 个元素的数组分配空间。您应该通过执行以下操作来初始化引用变量:

for(int i = 0; i < 2; i++){
    p[i] = new ResultList();
 }

回答by arshadImam

first of all you have created 5 element of ResultList type, but when inserting value you are inserting name and value wrong. you could use constructor to create and insert values to the array elements.

首先,您创建了 5 个 ResultList 类型的元素,但是在插入值时,您插入的名称和值是错误的。您可以使用构造函数为数组元素创建和插入值。

class ResultList {
    public String name;
    public Object value;
    public ResultList(String name,Object value){
        this.name = name;
        this.value = value;
        System.out.println(name+" --- "+value);
    }
}
public static void main(String[] args) {
        ResultList[] boll = new ResultList[5];
        boll[0] = new ResultList("myName","myValue");
    }

回答by Anup

class ResultList {
    public String name;
    public Object value;
    public ResultList() {}
}
 public class Test {
    public static void main(String[] args){
    ResultList[] boll = new ResultList[5];
    boll[0] = new ResultList(); //assign the ResultList objet to that index
    boll[0].name = "iiii";  
   System.out.println(boll[0].name);
   }
 }

Till you have created the ResultSet Object but every index is empty that is pointing to null reference that is the reason you are getting null. So just assign the Object on that index and then set the value.

直到您创建了 ResultSet 对象,但每个索引都是空的,指向空引用,这就是您获得空值的原因。所以只需在该索引上分配对象,然后设置值。

回答by Hrishabkumar jha

Either you can try this scenario or you can the make the variable "name" static in ResultList Class. So when the ResultList[] boll = new ResultList[5]; gets executed at that time all the variable from that class will gets assign

您可以尝试这种情况,也可以将 ResultList 类中的变量“名称”设为静态。所以当 ResultList[] boll = new ResultList[5]; 那时被执行,该类中的所有变量都将被赋值

public static void main(String[] args){
         ResultList[] boll = new ResultList[5];
    boll[0] = new ResultList();
    boll[0].name = "iiii";

    System.out.println(boll[0].name);
    }


public class ResultList {

    public  static String name;
    public  Object value;

    public ResultList() {}
}