0

I have declared a stack of integer array -

Stack<int[]> stack = new Stack<int[]>();

When I am pushing an object to stack using following code, I am getting an error -

stack.push({0,0});

But it works when I use the following code -

stack.push(new int[]{0,0});

So I am bit confused why the first way did not work. Does {0,0} not declare a new array object which can be pushed on the stack?

2
  • 1
    Short answer: no, it doesn't declare a new array object. Commented Aug 3, 2015 at 20:21
  • Your intuition was correct. In Java, you need to be specific about everything. Commented Aug 3, 2015 at 20:27

2 Answers 2

2

Just using the braces {0,0} doesn't by itself create and initialize a new array. You may be confused by the following syntax that makes this look like it's possible.

int[] someArray = {0, 0};

This syntax allows just the braces, and not the new int[] before it, only when it's part of a declaration. You don't have a declaration, so it's invalid syntax. Without a declaration, the new int[] part is required.

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

Comments

1

Try this:

stack.push(new int[] {0,0});

or,

int[] array = {0, 0} // creates a new array
stack.push(array);

Because, only {0, 0} does not create any new array, that's why you get errors. Read more.

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.