Reputation: 1734
I have a stack of Integer in Java and I would like to know is there other way to increment "the last pushed item" by one without poped it first.
My current solution is
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2); // Increment 2 to 3
Integer last = stack.pop();
stack.push(last+1);
I tried the following but not working
Integer last = stack.peek();
last+=1;
I thought it would work because last is a reference to the last element in the stack and it got incremented.
Upvotes: 1
Views: 5284
Reputation: 136162
You need mutable long object for that, e.g. org.apache.commons.lang3.mutable.MutableLong
or java.util.concurrent.atomic.AtomicLong
. Then you can modify it
stack.peek().increment();
Upvotes: 1
Reputation: 183602
In Java, the Integer
class is immutable, meaning that an Integer
object can never be modified. This:
last += 1;
is really just shorthand for this:
last = Integer.valueOf(last.intValue() + 1);
That is, it actually creates (or retrieves) a different Integer
instance, whose value is one greater than the value of the previous Integer
instance.
If you want to be able to modify the object at the top of the stack, you'll need to put mutable objects on the stack. You can create your own IntWrapper
or IntHolder
or MutableInteger
class for that. (But I don't particularly recommend this.)
Upvotes: 8
Reputation: 19856
with last+=1;
you assign another object to last
. Therefore, the stack is not manipulated.
Upvotes: 2