1

I have an array of four stacks. And I am initializing it using foreach loop.

Stack s[]=new Stack[4];

for(Stack n:s)
{
    n=new Stack();   
}   

System.out.println(s[0]);

But the problem with this is it prints null. But when I replaced this with normal for loop

Stack s[]=new Stack[4];

for(int i=0;i<4;i++)
{
    s[i]=new Stack();   
}       

System.out.println(s[0]);

it prints []. I tried it with other java collections LinkedList,ArrayList etc but all are having same behaviour. My question is why the first method is not working, it used to work everywhere ?

2 Answers 2

1

Here :

for(Stack n:s)
{
    n = new Stack();   
}  

n is a local variable that refers to the current array element while the current value is null.
But as you assign a new object to n (new Stack()), n doesn't reference any longer the array element but the new created object.
The new created object is finally discarded at each iteration and the current array element stays null.


This foreach code on an array :

for(Stack n : s){
    n = new Stack();   
}   

could be translated into this code by the compiler :

for (int i = 0; i < s.length; i++) {
    Stack n = s[i]; // the array element is stored in a local variable
    n = new Stack(); // the n local variable refers to a new Stack object
                     // but is not assigned to s[i]
}

While when you use this syntax :

s[i]=new Stack();   

you explicitly assign the new created object to the i element of the array.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like this to populate your array.

    Stack s[]=new Stack[4];
    Arrays.setAll(s, i -> new Stack()); 
    System.out.println(s[0]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.