Skip to main content

How to Use Generic Types like List<String> in Java

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

A generic type such as List or Map takes the type of what it holds in angle brackets: List<String> is a list of strings, and Map<String, Integer> maps strings to whole numbers. Java then checks every value that goes in when the code compiles, and gives back the right type when a value comes out.

Syntax​

Syntax
Type<Argument> name = new Class<>();
Type<Argument1, Argument2> name = new Class<>();
PartWhat it does
TypeA generic interface or class, such as List or Map.
<Argument>The type argument: the type of what it holds, such as String. It must be a reference type, such as Integer, not a primitive type such as int.
<Argument1, Argument2>Two type arguments, for a type that takes two, such as a Map's key type and value type.
nameThe variable's name.
new Class<>()Creates the object, such as an ArrayList or a HashMap. The empty <> takes its type arguments from the left side.

The Java Tutorials, Why Use Generics?: "A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find." Generic Types names the empty brackets: "This pair of angle brackets, <>, is informally called the diamond."

The Example​

The example makes a List<String> of roles and a Map<String, Integer> of limits, and calls a String method on an element of the list without a cast. A changed version then tries to add the number 42 to the list of strings.

Prerequisites​

  • A JDK 11 or later, which can run a single .java file directly. This guide uses OpenJDK 25.0.5.1.

Step 1: Write the Code​

Create a file named Main.java:

Main.java, which creates a list of String with new ArrayList and the diamond, adds editor and viewer, prints the first element in capital letters, then creates a map of String to Integer, puts pro 500 and prints the value for pro.

Main.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {

public static void main(String[] args) {
// A list that holds only Strings. The empty <> takes its type from the left side.
List<String> roles = new ArrayList<>();
roles.add("editor");
roles.add("viewer");

// get returns a String, so String methods work on it without a cast.
String first = roles.get(0);
System.out.println(first.toUpperCase());

// A map with String keys and Integer values: one type argument for each.
Map<String, Integer> limits = new HashMap<>();
limits.put("pro", 500);
System.out.println(limits.get("pro"));
}
}

Step 2: Run It​

Terminal
java Main.java
Output
EDITOR
500

java Main.java compiles the file in memory and runs it. The command is the same in zsh, bash and PowerShell.

Step 3: Add a Number to a List of Strings​

Replace Main.java with a version that adds 42 to roles:

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

public class Main {

public static void main(String[] args) {
List<String> roles = new ArrayList<>();
roles.add("editor");
roles.add(42);
System.out.println(roles);
}
}
Terminal
java Main.java
Output
Main.java:9: error: no suitable method found for add(int)
roles.add(42);
^
method List.add(String) is not applicable
(argument mismatch; int cannot be converted to String)
method List.add(int,String) is not applicable
(actual and formal argument lists differ in length)
1 error
error: compilation failed

A zsh terminal where java Main.java prints EDITOR and 500, then, for the changed file, fails to compile with error: no suitable method found for add(int), because int cannot be converted to String.

What Happened​

  • roles.get(0) returned a String, so first.toUpperCase() worked without a cast and printed EDITOR.
  • limits.get("pro") returned the Integer 500. The map has two type arguments: String for its keys and Integer for its values.
  • The changed version never ran. The compiler checked roles.add(42) against List<String> and stopped with no suitable method found for add(int), because "int cannot be converted to String".

Without a type argument, Java accepts the number. A raw List that held "editor" and 42 compiled with two [unchecked] warnings, and then failed only when the program ran, with ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String at the line that read the number back as a String.

Common Mistakes​

MistakeWhat happensDo this instead
List<int>error: unexpected type, with required: reference and found: intUse the wrapper class: List<Integer>
A raw List, without a type argument[unchecked] warnings, then a ClassCastException when a value of the wrong type comes outAlways give the type argument
Writing the diamond on the left, as in List<> roleserror: illegal start of typeWrite the type argument on the left, and the diamond after new

Troubleshooting​

SymptomLikely causeFix
error: no suitable method found for add(int), with int cannot be converted to StringA value of the wrong type goes into a List<String>Add a String, or change the type argument
error: incompatible types: Object cannot be converted to Stringget on a raw List returns an ObjectDeclare it as List<String>
warning: [unchecked] unchecked call to add(E) as a member of the raw type ListThe list has no type argumentDeclare it with one, such as List<String>

FAQ​

What's the difference between a type parameter and a type argument?​

The tutorial: "the T in Foo<T> is a type parameter and the String in Foo<String> f is a type argument". List is declared with a type parameter named E, and String is the type argument in List<String>.

Why do I write Integer and not int?​

A type argument must be a reference type, and int is a primitive type. Java converts between the two by itself, which is why limits.put("pro", 500) works with a plain 500.

Since which Java version does the diamond work?​

Java SE 7. The tutorial: "In Java SE 7 and later, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context."

Conclusion​

A type argument in angle brackets tells Java what a List, a Map or another generic type holds. The compiler then checks every value that goes in, values come out with the right type and need no cast, and the diamond <> after new saves writing the type arguments twice.

Additional Resources​