import java.util.Stack;
public class StackIntro {
public static void main(String[] args){
Stack clapper = new Stack();
for( int i=0; i<11; i++){
clapper.push(i);
}
while(!clapper.isEmpty()){
System.out.print ( clapper.pop() ); //FILO
System.out.print ( ',' );
if(clapper.size()==1){
System.out.print(clapper.pop()); //FILO
System.out.println("...");
}
}
System.out.println("Lift-off.");
clapper.removeAllElements();
}
}
So basically I just wanted to see how numbers go in and out of a stack. The FILO comment shows this. I was told that I should actually change line 8 :
clapper.push(i); //previous
clapper.push(new Integer(i)); //new
I don't understand what this would accomplish, or the difference between the two.
Although due to autoboxing both lines of code result in an Integer
object with value 1
being pushed on the stack, the two lines do not have exctly the same effect.
Autoboxing uses the Integer cache, which is required by the JLS for values from -128
to 127
, such that the resulting Integer
instance is the same instance for any value in that range.
However, invoking the int
constructor creates a new Integer
instance every time it's called.
Consider:
Integer a = 1; // autoboxing
Integer b = 1; // autoboxing
System.out.println(a == b); // true
Integer c = new Integer(1);
Integer d = new Integer(1);
System.out.println(c == d); // false
This distinction may cause different behaviour in your program if you use ==
(object identity) when comparing values pushed and popped to/from the stack instead of equals()
.
This would not accomplish much, very possibly not anything at all.
The idea is that clapper.push(T)
accepts an object, but i
is not an object, it is a primitive, so the compiler will automatically box it into an Integer
object before passing it to clapper.push()
.
Auto-boxing was not a feature of java from the beginning, so there may still exist some old-timers who are uncomfortable with it. But that should be entirely their own problem. Java has come a long way since then. Auto-boxing is taken for granted, we do not even give it any thought anymore.
Passing i
and having the compiler auto-box it is exactly the same as as passing new Integer(i)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With