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

Collections of Collections: Nested Generics

Working with nested generic types like ArrayList<ArrayList<String>> and proper syntax.

Collections of Collections: Nested Generics

You'll learn how to use nested generic types like ArrayList<ArrayList<String>> to create multi-dimensional data structures.

The Core Idea

Sometimes you need a collection where each element is itself a collection. Think of a spreadsheet: it's a list of rows, where each row is a list of cells. In Java, you express this by nesting one generic type inside another: ArrayList<ArrayList<String>> means "an ArrayList where each element is an ArrayList of Strings."

Proper Syntax

The key is placing one complete parameterized type inside the angle brackets of another:

// A list of lists of strings
ArrayList<ArrayList<String>> table = new ArrayList<>();

// Create and add inner lists
ArrayList<String> row1 = new ArrayList<>();
row1.add("Alice");
row1.add("Bob");
table.add(row1);

ArrayList<String> row2 = new ArrayList<>();
row2.add("Charlie");
row2.add("Diana");
table.add(row2);

// Accessing elements: first the outer index, then the inner
String firstPersonInSecondRow = table.get(1).get(0); // "Charlie"

Notice how you retrieve elements: table.get(1) returns an ArrayList<String>, then .get(0) retrieves the first String from that inner list.

Common Use Cases

  • Grids and matrices: ArrayList<ArrayList<Integer>>
  • Grouped data: ArrayList<HashSet<String>> for sets of tags per item
  • Key-value collections: ArrayList<HashMap<String, Integer>>

Syntax Tips

Each nesting level needs its own complete type argument. ArrayList<ArrayList<String>> is correct; ArrayList<ArrayList> loses type safety (raw type warning).

Key Takeaway: Nested generics like ArrayList<ArrayList<String>> let you build collections of collections with full type safety—just nest the complete parameterized type inside the outer type's angle brackets.