Mega Code Archive

 
Categories / Java Tutorial / Generics
 

Nested generic type

A generic type is itself a type and can be used as a type variable. For example, if you want your List to store lists of strings: List<List<String>> myListOfListsOfStrings; To retrieve the first string from the first list in myList, you would use: String s = myListOfListsOfStrings.get(0).get(0); Working with List of Lists import java.util.ArrayList; import java.util.List; public class MainClass {   public static void main(String[] args) {     List<String> listOfStrings = new ArrayList<String>();     listOfStrings.add("Hello again");     List<List<String>> listOfLists = new ArrayList<List<String>>();     listOfLists.add(listOfStrings);     String s = listOfLists.get(0).get(0);     System.out.println(s); // prints "Hello again"   } }