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

Parameterized Types as Type Arguments

Master using one generic type as the type argument for another, enabling complex type compositions.

Parameterized Types as Type Arguments

You'll learn how to nest generic types by using one parameterized type (like List<String>) as the type argument for another generic type.

The Core Idea

So far, you've used simple types like String or Integer as type arguments: List<String> or Box<Integer>. But here's the powerful part: a parameterized type itself can be a type argument. You can create compositions like List<List<String>> (a list of lists) or Box<List<Integer>> (a box containing a list).

Think of it like nesting containers: a box that holds another box, which holds the actual item. Each layer adds structure and type safety.

How It Works

// A list of strings
List<String> names = new ArrayList<>();

// A list of lists of strings (nested parameterized types)
List<List<String>> groupsOfNames = new ArrayList<>();
groupsOfNames.add(names);

// A box containing a list of integers
Box<List<Integer>> boxOfNumbers = new Box<>();
List<Integer> numbers = new ArrayList<>();
numbers.add(42);
boxOfNumbers.setValue(numbers);

Notice that List<String> is itself the type argument for the outer List. The outer container is generic, and its type parameter is satisfied by another generic type.

Why This Matters

This composition lets you build complex data structures while maintaining type safety. A List<List<Integer>> guarantees that you have lists of integers, not lists of strings or mixed types. The compiler enforces correctness at every level of nesting.

You can nest as deeply as needed: Map<String, List<Set<Integer>>> is perfectly valid (though readability suffers with excessive nesting).

Key Takeaway: Parameterized types can serve as type arguments for other generic types, enabling safe, composable data structures like lists of lists or boxes of collections—Java's type system validates every layer.