What good is doing here with the new Integer?

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 the numbers came in and out of the stack. The FILO comment shows this. I was told that I should change line 8:

clapper.push(i); //previous

clapper.push(new Integer(i)); //new

I do not understand what this will accomplish, or the difference between the two.

+4
source share
2 answers

Although due to autoboxing, both lines of code lead to the fact that an object Integerwith a value 1is pushed onto the stack, two lines do not have the same effect.

Autoboxing uses the Integer cache that JLS requires for values ​​from -128to 127, so the resulting instance Integeris the same instance for any value in this range.

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

, == ( ) , / equals().

+5

, , .

, clapper.push(T) , i , , Integer, clapper.push().

- java , , . . Java . - , .

i , new Integer(i).

+4

Source: https://habr.com/ru/post/1658127/


All Articles