简体   繁体   中英

Java - allocation in enhanced for loop

I have small problem in java with allocation of my object in "enhanced for loop". I tried something like this, which gives me later nullPointerException:

SomeClass tab[] = new SomeClass[100];
for( SomeClass x : tab){
  x = new SomeClass();
}

So... Earlier I code in C++ and It was possible to edit in any way (and sure also allocate memory) object, when just add & operator, like this:

SomeClass *tab = new SomeClass[100];
for( auto & x : tab){
  x = new SomeClass();
}

...and everything works well. But how is it in java? Is there any way to use this for loop when allocate some memory or not?

No, you cannot use an enhanced for loop to initialize the elements of an array. The declared variable, here x , is a separate variable that refers to the current element in the array. It's null here because you just declared the array. You are changing x to refer to a new SomeClass , but that doesn't affect the array at all.

0    | 1    | 2    | ...
-------------------------
|    |      |      | ...
v
null <--- x

After assignment to x:

0    | 1    | 2    | ...
-------------------------
|    |      |      | ...
v
null

x --> new SomeClass()

Java variables are different from C++ references in this behavior. Assigning a Java reference variable does not affect anything else that might refer to the same object.

You must use an array access expression, which requires an index. A standard for loop will work here.

SomeClass tab[] = new SomeClass[100];
for (int i = 0; i < tab.length; i++)
{
    tab[i] = new SomeClass();
}

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