Java - Autoboxing/Unboxing and Collections

Why use Autoboxing/Unboxing with Collections

Autoboxing/unboxing works well with Collections which work only with reference types.

You cannot use primitive types in collections.

To store primitive types in a collection, wrap the primitive value before storing it, and unwrap it after retrieving it.

Suppose you have a List and you want to store integers in it.

List list = new ArrayList();
list.add(new Integer(101));
Integer a = (Integer)list.get(0);
int aValue = a.intValue();

The autoboxing/unboxing wrapps the primitive type to a reference type, and the above code may be rewritten as

List list = new ArrayList();
list.add(101); // Autoboxing will work here
Integer a = (Integer)list.get(0);
int aValue = a.intValue();

Demo

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

public class Main {
  public static void main(String[] args) {
    List list = new ArrayList();
    list.add(101); // Autoboxing will work here
    Integer a = (Integer) list.get(0);
    int aValue = a.intValue();

    System.out.println(aValue);//ww  w  .j av  a2s  .c o  m
  }

}

Result

Related Topic