Autoboxing with Generics in Java

Published by user on

In this post, we are going to look at how autoboxing works with Generics in Java.

Autoboxing is a feature that got introduced in Java 1.5 and it plays a very important role while using generics.

As we know generic collections can only hold object types. But Java also has support for primitive types i.e. int, double, float. Now, the problem is how to use generics with these primitive types.

To solve this problem Java introduced the concept wrapper classes, autoboxing, and unboxing.

Wrapper Class

Wrapper classes are the object representation of primitive types e.g. int data type has Integer wrapper class and so on.

Autoboxing

Autoboxing is where Java automatically converts primitive data type to wrapper type.

Integer a = 10;

The process of assigning primitive 10 to the Integer wrapper class is autoboxing.

Unboxing

Java converts wrapper class instance into associated primitive type. This is unboxing. E.g. we assigned the Integer value to int data type.

Integer b = new Integer(10);
// this is unboxing
int c = b;

Let’s look at the program.

Program: Autoboxing and unboxing with Generics

import java.util.ArrayList;
import java.util.List;

// This program shows
// how to add primitive types
// in generic list using autoboxing
public class AutoboxingWithGenerics {
	public static void main(String[] args) {

		// Create an instance of ArrayList
		// of type Integer
		List<Integer> numbers = new ArrayList<>();

		// Add primitive int elements
		// This is autoboxing
		numbers.add(10);
		numbers.add(20);
		numbers.add(30);

		// Print the elements
		System.out.println("Elements : " + numbers);

		// This is unboxing
		int unboxedValue = numbers.get(0);

		// Print the value
		System.out.println("Value is : " + unboxedValue);
	}
}

Output

Elements : [10, 20, 30]
Value is : 10

Explanation

  • Create an instance of a list that can hold Integer values
  • Now, try to add a primitive int to the list
  • Add 10, 20, and 30 to the list
  • Adding these elements is possible only because Java converts primitive int type to the wrapper Integer type
  • Finally, Java can also convert the Integer wrapper class to primitive int type. This refers to unboxing
Categories: Java