在这里使用新的Integer有什么用呢?

Chu*_*aba 4 java

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

所以基本上我只是想看看数字是如何进出堆栈的.FILO评论显示了这一点.我被告知我应该改变第8行:

clapper.push(i); //previous

clapper.push(new Integer(i)); //new
Run Code Online (Sandbox Code Playgroud)

我不明白这会实现什么,或者两者之间的区别.

Boh*_*ian 5

虽然由于自动装箱这两行代码导致一个Integer对象的值1被推到堆栈上,但这两行并没有完全相同的效果.

自动装箱使用整数缓存,这是由JLS所需值从-128127,使得所得到的Integer实例是相同的为在该范围内的任何值的实例.

但是,调用int构造函数会在每次调用时创建一个 Integer实例.

考虑:

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
Run Code Online (Sandbox Code Playgroud)

如果==在比较推送和弹出/从堆栈中弹出的值而不是使用(对象标识)时,这种区别可能会导致程序中出现不同的行为equals().