-4

While working with stacks/queues in pop() or dequeue() operations I had bits of code which went like this:

myarray[t--]=null;

The implementation was in the form of an array of ints. I get an error which goes like " cannot be converted to int". Now I realize this reassigning to null isnt explicitly necessary for this implementation since I'm keeping track of the top of the stack. But anyway, how do I overcome this error?

Neodymia
  • 93
  • 9

1 Answers1

1

Primitives such as int cannot be null. Use an object instead, the class Integer in this case. See this Question for more discussion.

Please declare your array myarray as follows:

int size =10; // size of array
Integer[] myarray=new Integer[size];

Now, you can assign as:

myarray[t--]=null;
Community
  • 1
  • 1
Sanjeev Saha
  • 2,632
  • 1
  • 12
  • 19
  • So I take it that using Integer is a prereq for such an assignment? Thanks. – Neodymia Jun 28 '16 at 08:14
  • Yes @Neodymia you may not assign `null` to an array of primitives such as `int`. You need to use wrapper class `Integer` for such scenario. – Sanjeev Saha Jun 28 '16 at 08:21
  • @Neodymia No need for an Integer object when assigning a value, such as `myArray[t] = 7 ;`. Java will conveniently create an `Integer` object from your `int` primitive value. See the [Tutorial on autoboxing](http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html). – Basil Bourque Jun 28 '16 at 08:22