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?

arodriguezdonaire
  • 4,863
  • 22
  • 48

2 Answers2

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.

rgettman
  • 167,281
  • 27
  • 248
  • 326
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.

Community
  • 1
  • 1
rakeb.mazharul
  • 5,423
  • 3
  • 18
  • 39