简体   繁体   中英

Java Object Reference Array Initialization

In java, how do object references in an array initialization work?

For example, this works fine:

SomeObject object1;
SomeObject object2;

// ***

object1 = new SomeObject();
object2 = new SomeObject();

SomeObject[] objects = {object1, object2};

// processing objects

However, if I put the array initialization at the "***" mark, I later get a NullPointerException when processing the array elements. Why? The array contains object references already, why does it matter if I initialize the said objects before or after initializing the array?

The array contains object references already, why does it matter if I initialize the said objects before or after initializing the array?

When calling SomeObject[] objects = {object1, object2}; you will get an array whose elements are assigned the values of object1 and object2 . Note that in Java a reference is just the value of the address, ie when you access object1 before assigning it, the value of that reference will still be null .

That's why you get null elements in your array when you build it before intializing the references.

At the point of *** , object1 and object2 are declared, but have not yet been assigned. In Java, this means that they are both null.

So when you create array with them, you are essentially doing this:

SomeObject[] objects = { null, null };

Later when you process the elements of the array, you get a NullPointerException because, well, you have stored null s in your array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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