Course contentsShow
← Java
Lesson 904 of 2,87021. Generics FundamentalsFree lesson

Autoboxing with Generic Collections

How primitive types are automatically boxed when used with generic collections like ArrayList<Integer>.

Autoboxing with Generic Collections

What you'll learn: How Java automatically wraps primitive types into their object equivalents when working with generic collections.


The Problem Generics Solve

You already know that type arguments in generics cannot be primitives—you must write ArrayList<Integer>, not ArrayList<int>. But what happens when you try to add an int value to that list? Java doesn't make you manually wrap it in an Integer object. Instead, it handles the conversion automatically through autoboxing.

What Is Autoboxing?

Autoboxing is Java's automatic conversion of primitive types to their corresponding wrapper classes. When you add a primitive value to a generic collection, Java silently boxes it for you:

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(42);  // int 42 is automatically boxed to Integer

Behind the scenes, Java transforms 42 into Integer.valueOf(42). You write cleaner code without manual conversion.

Unboxing Works Too

The reverse process, unboxing, happens when retrieving values:

int value = numbers.get(0);  // Integer is unboxed to int

Java automatically calls .intValue() on the Integer object.

Complete Example

ArrayList<Double> prices = new ArrayList<>();
prices.add(19.99);      // double → Double (autoboxing)
prices.add(29.95);      // double → Double

double total = 0.0;
for (double price : prices) {  // Double → double (unboxing)
    total += price;
}

Analogy: Think of autoboxing like an automatic gift-wrapping service. When you hand over a primitive value (the raw item), Java wraps it in its object box before storing it. When you retrieve it, Java unwraps it for you.

Key Takeaway: Java automatically boxes primitives to wrapper objects when adding to generic collections and unboxes them when retrieving, making collections like ArrayList<Integer> feel natural to use with primitive values.