Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What good does using new Integer here do?

Tags:

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();
    }
}

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.

like image 582
Chuck B Ihekwaba Avatar asked Jan 05 '23 05:01

Chuck B Ihekwaba


2 Answers

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().

like image 92
Bohemian Avatar answered Jan 19 '23 09:01

Bohemian


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).

like image 42
Mike Nakis Avatar answered Jan 19 '23 09:01

Mike Nakis