Skip to content

Java generics input type vs returned type

I’m learning about generics and am slightly confused. I’m confused about the difference between the input type and returned type for a class using generics.

   Stack<Integer> even = new Stack<>();
    // pushing values in stack

    System.out.println("pop => " + even.pop());

We are pushing in an int value of 0 and 2. But the first print statement will print “Integer”. If the stack is declared with Integer as its generic type, why are we able to push in a primitive “int”? If we can push in a primitive “int” why is the pop() class returning a wrapper class “Integer”?

I’m clearly misunderstanding something about generics.



It happens because of someting called autoboxing.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

The simplest example:

Character ch = 'a';

That is what happens here:

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)

The compiler creates an Integer object from i and adds the object to the list.

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)

The same thing for you stack.

User contributions licensed under: CC BY-SA
6 People found this is helpful