Java Generics: Generic Classes and Generic Methods
Learn why Java generics exist and how to use them: type parameters versus Object and casts, defining a generic class like Pair<T>, naming conventions, the diamond operator, generic methods, type inference and how to decode inference errors.
kvi5hnuCode Sprout team member12 min readOn this page
Generic classes and methods have type parameters. They let you describe precisely which types a piece of code works with, and let the compiler check it. Before generics, programmers wrote code for "any type" using Object, which was both clumsy and unsafe. Generics arrived in Java 5, the most significant change to the language at the time, and now every collection class, the stream library, Optional, Comparator and much more depend on them.
This part of the course explains what you need to know to use generics confidently, read the signatures in the API documentation, and write your own generic code. This first article covers the basics: why generics exist, generic classes and generic methods.
Why generic programming?
Generic programming means writing code that can be reused for objects of many different types. You don't want separate list classes for String and File objects, and you don't need them: the single class ArrayList collects objects of any class.
ArrayList existed before generics did. Back then, generic programming was done with inheritance. The class simply kept an array of Object references:
public class ArrayList { // before generic classes
private Object[] elementData;
. . .
public Object get(int i) { . . . }
public void add(Object o) { . . . }
}
This has two problems. First, every retrieved value needs a cast:
ArrayList files = new ArrayList();
. . .
String filename = (String) files.get(0);
Second, there's no error checking. You can add values of any class:
files.add(new File(". . ."));
That compiles and runs without complaint. The error surfaces somewhere else, maybe much later, when a cast of the result of get to String fails with a ClassCastException.
The advantage of type parameters
Generics offer a better solution: type parameters. ArrayList now has a type parameter for its element type:
var files = new ArrayList<String>();
This makes the code easier to read: you can tell at a glance that this list holds strings. If you declare the variable with an explicit type, you can leave out the type argument in the constructor call with the diamond syntax:
ArrayList<String> files = new ArrayList<>();
The omitted type is inferred from the variable's type. Since Java 9, the diamond also works with anonymous subclasses:
ArrayList<String> passwords = new ArrayList<>() { // diamond OK in Java 9+
public String get(int n) { return super.get(n).replaceAll(".", "*"); }
};
The compiler makes good use of the type information. No cast is needed for get, because the compiler knows the return type is String, not Object:
String filename = files.get(0);
The compiler also knows that add on an ArrayList<String> takes a String. That's much safer than an Object parameter, because the compiler can reject wrong insertions:
files.add(new File(". . .")); // can only add String objects to an ArrayList<String>
won't compile. A compiler error is far better than a ClassCastException at run time. This is the whole appeal of type parameters: programs become easier to read and safer.
Who wants to be a generic programmer?
Using a generic class like ArrayList is easy. Most programmers simply use ArrayList<String> as if it were built into the language, like String[].
Implementing a generic class is harder. Users will plug in all sorts of types for your type parameters and expect everything to work without odd restrictions or confusing error messages. A generic programmer has to anticipate all those future uses.
Here's a typical problem the library designers faced. ArrayList has a method addAll that adds all elements of another collection. It should be possible to add all elements of an ArrayList<Manager> to an ArrayList<Employee>, since every manager is an employee, but not the other way around. How can one call be allowed and the other rejected? Java's answer is the wildcard type, a rather abstract but powerful concept that you'll meet later in this part.
Generic programming has three levels of skill:
- Using generic classes, typically collections, without thinking about how they work. Most application programmers stay here until something goes wrong.
- Troubleshooting: understanding enough to fix confusing error messages when mixing generic classes or working with legacy code that predates type parameters.
- Implementing your own generic classes and methods.
Application programmers rarely write a lot of generic code. The JDK developers have done the heavy lifting. As a rule of thumb, code that used to need lots of casts from very general types, such as Object or the Comparable interface, benefits from type parameters. This part teaches everything needed for level 3, but you'll most often use it for level 2.
Defining a simple generic class
A generic class is a class with one or more type variables. We'll use a simple Pair class as the running example, so we can focus on generics without the distraction of data storage details:
public class Pair<T> {
private T first;
private T second;
public Pair() { first = null; second = null; }
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
}
The type variable T is introduced in angle brackets < > after the class name. Inside the class, it is used like any type: for fields, method parameters, return types and local variables:
private T first; // uses the type variable
A class can have several type variables. A pair whose two parts have different types would be declared like this:
public class Pair<T, U> { . . . }
You instantiate the generic type by substituting a type for the type variable, such as Pair<String>. You can think of the result as an ordinary class with constructors
Pair<String>()
Pair<String>(String, String)
and methods
String getFirst()
String getSecond()
void setFirst(String)
void setSecond(String)
In other words, a generic class acts as a factory for ordinary classes:

This is a compile-time view. At run time, as you'll see in the article on type erasure, there's still just one class Pair.
The demo program below uses Pair in a static minmax method that walks through an array of strings and finds the minimum and maximum at the same time. A Pair returns both results. Recall that compareTo returns 0 for equal strings, a negative number if the first comes before the second in dictionary order, and a positive number otherwise.
Generic methods
You can also define a single method with type parameters:
class ArrayAlg {
public static <T> T getMiddle(T... a) {
return a[a.length / 2];
}
}
ArrayAlg is an ordinary class, but getMiddle is a generic method, as the angle brackets and the type variable show. The type variable list goes after the modifiers (public static) and before the return type. Generic methods can be defined in ordinary classes and in generic classes. In a generic class, a method can declare its own type variables in addition to the class's. The demo's map method in Pair<T> does that with <R>.
To call a generic method, you can put the actual type in angle brackets before the method name:
String middle = ArrayAlg.<String>getMiddle("John", "Q.", "Public");
Usually, though, you leave it out. The compiler has enough information to infer the type: it matches the argument types against T... and concludes that T must be String:
String middle = ArrayAlg.getMiddle("John", "Q.", "Public");
When inference goes wrong
Type inference for generic methods almost always works smoothly. Occasionally it doesn't, and you have to decipher an error message. Consider:
double middle = ArrayAlg.getMiddle(3.14, 1729, 0);
The compiler autoboxes the arguments into one Double and two Integer objects and looks for a common supertype for T. There isn't a single obvious one: both Number and Comparable (itself generic) fit, as do Constable and ConstantDesc from java.lang.constant. So T is inferred as an intersection type of all of them, and that doesn't convert to double. Current versions of javac report:
error: incompatible types: inferred type does not conform to upper bound(s)
inferred: INT#1
upper bound(s): Double,Object
where INT#1,INT#2 are intersection types:
INT#1 extends Number,Comparable<? extends INT#2>,Constable,ConstantDesc
The fix here is to write all arguments as double values: getMiddle(3.14, 1729.0, 0.0). Then T is simply Double.
var can hold an intersection type, which the demo shows: var mixed = ArrayAlg.getMiddle(3.14, 1729, 0); compiles, and mixed can then be assigned to a Number or a Comparable<?>.
A complete example
import java.util.*;
public class Solution {
public static void main(String[] args) {
// 1. before generics: see rawListDemo below
rawListDemo();
// 2. with a type parameter: no cast, and the compiler checks every add
var names = new ArrayList<String>();
names.add("report.txt");
// names.add(42); // compile-time error
String name = names.get(0);
System.out.println("name = " + name);
// 3. our own generic class
String[] words = { "Mary", "had", "a", "little", "lamb" };
Pair<String> mm = ArrayAlg.minmax(words);
System.out.println("min = " + mm.getFirst());
System.out.println("max = " + mm.getSecond());
// 4. two type variables, and the diamond
Pair2<String, Integer> entry = new Pair2<>("answer", 42);
System.out.println(entry.first() + " -> " + entry.second());
// 5. generic methods: explicit type argument, or (usually) inferred
String middle = ArrayAlg.<String>getMiddle("John", "Q.", "Public");
String inferred = ArrayAlg.getMiddle("John", "Q.", "Public");
System.out.println(middle + " " + inferred);
// the inferred type of a mixed call is an intersection type; var accepts it
var mixed = ArrayAlg.getMiddle(3.14, 1729, 0);
Number n = mixed; // it is a Number...
Comparable<?> c = mixed; // ...and a Comparable
System.out.println(mixed + " is a " + mixed.getClass().getSimpleName() + ", " + n.intValue() + ", " + (c != null));
double fixed = ArrayAlg.getMiddle(3.14, 1729.0, 0.0); // all doubles: T is Double
System.out.println(fixed);
// 6. a generic method inside a generic class: T from the class, R from the method
Pair<String> p = new Pair<>("ant", "bee");
Pair<Integer> lengths = p.map(String::length);
System.out.println(lengths.getFirst() + ", " + lengths.getSecond());
// 7. a diamond with an anonymous subclass (Java 9+)
Comparator<String> byLength = new Comparator<>() {
@Override
public int compare(String a, String b) { return Integer.compare(a.length(), b.length()); }
};
var sorted = new ArrayList<>(List.of(words));
sorted.sort(byLength);
System.out.println(sorted);
}
/** Before generics: an ArrayList of Object, casts, and late failures. */
@SuppressWarnings({ "rawtypes", "unchecked" })
static void rawListDemo() {
ArrayList files = new ArrayList();
files.add("report.txt");
files.add(42); // compiles: anything goes
String first = (String) files.get(0); // cast needed
System.out.println("first = " + first);
try {
String second = (String) files.get(1); // fails only at run time
System.out.println(second);
} catch (ClassCastException e) {
System.out.println("ClassCastException: Integer is not a String");
}
}
}
class Pair<T> {
private T first;
private T second;
public Pair() { first = null; second = null; }
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
/** A generic method in a generic class. */
public <R> Pair<R> map(java.util.function.Function<T, R> f) {
return new Pair<>(f.apply(first), f.apply(second));
}
}
/** Generic records work too: the components get the type variables. */
record Pair2<T, U>(T first, U second) { }
class ArrayAlg {
/**
* Gets the minimum and maximum of an array of strings.
* @param a an array of strings
* @return a pair with the min and max values, or null if a is null or empty
*/
public static Pair<String> minmax(String[] a) {
if (a == null || a.length == 0) return null;
String min = a[0];
String max = a[0];
for (int i = 1; i < a.length; i++) {
if (min.compareTo(a[i]) > 0) min = a[i];
if (max.compareTo(a[i]) < 0) max = a[i];
}
return new Pair<>(min, max);
}
@SafeVarargs
public static <T> T getMiddle(T... a) {
return a[a.length / 2];
}
}
first = report.txt
ClassCastException: Integer is not a String
name = report.txt
min = Mary
max = little
answer -> 42
Q. Q.
1729 is a Integer, 1729, true
1729.0
3, 3
[a, had, Mary, lamb, little]
The rawListDemo method shows the pre-generics world: the bad add compiles, and the failure only shows up as a ClassCastException when the value is used. With ArrayList<String>, the same mistake is a compile-time error. That line is commented out in main, because it wouldn't compile.
Common questions
Can I use a primitive type such as int as a type argument?
Not yet. Type arguments must be reference types, so you write List<Integer> and rely on autoboxing. Project Valhalla is working on value classes and, later, generics over primitives, but no released Java version (up to Java 27) allows List<int>.
When should I write the type argument explicitly, as in ArrayAlg.<String>getMiddle(...)?
Rarely. Inference handles almost every call. You need an explicit type argument mainly when there are no arguments to infer from, for example Collections.<String>emptyList() passed directly to a method expecting a more specific type, or when inference picks an intersection type you don't want.
What is the difference between a generic method in a generic class and an ordinary method that uses the class's type variable?
A method such as T getFirst() uses the class's T, which is fixed when you create the object. A generic method such as <R> Pair<R> map(Function<T, R> f) declares its own type variable, which can be different at every call. Static methods can't use the class's type variable at all, so a static generic helper always declares its own.
Should I use a generic record or a generic class for a simple pair?
Use a record when the pair is just immutable data: you get the constructor, accessors, equals, hashCode and toString automatically. Use a class when you need mutability, validation that changes the values, or hidden state.
What does the diamond <> actually do?
It tells the compiler to infer the constructor's type arguments from the context, usually the variable's declared type. List<String> names = new ArrayList<>(); is exactly the same as writing new ArrayList<String>(). With var, the diamond has nothing to infer from and gives ArrayList<Object>, so write the type argument there.
Summary
- Generics let classes and methods take type parameters, replacing
Objectplus casts with checked, readable types. - A generic class declares type variables after its name:
class Pair<T>,class Pair<T, U>. Use them like types inside the class. Pair<String>behaves like an ordinary class withStringin place ofT. A generic class is a factory for such classes.- Conventional names:
Eelement,K/Vkey/value,T/U/Sany type,Rresult. - The diamond
new ArrayList<>()infers type arguments, also for anonymous classes since Java 9. - A generic method declares type variables before its return type:
public static <T> T getMiddle(T... a). Callers can supply<String>explicitly, but usually the compiler infers it. - Mixed argument types can lead to intersection types and confusing errors. Make the arguments consistent, or provide the type argument explicitly.
Practice Questions
Name two problems with collections of Object that generics solve.
Every retrieved element needs a cast, and nothing stops you from inserting the wrong type. That error only shows up later as a ClassCastException. Generics remove the casts and turn wrong insertions into compile-time errors.
Where does the type variable list go in a generic method declaration?
After the modifiers and before the return type, as in public static <T> T getMiddle(T... a).
Write the declaration of a generic method firstOrDefault that returns the first element of a List<T>, or a given default value if the list is empty.
public static <T> T firstOrDefault(List<T> list, T defaultValue) { return list.isEmpty() ? defaultValue : list.get(0); }
Why does double d = ArrayAlg.getMiddle(1.5, 2, 3); fail to compile, and how can you fix it?
The arguments box to Double, Integer and Integer, so T is inferred as an intersection of their common supertypes (Number, Comparable<...>, ...), which can't be converted to double. Pass consistent types, for example getMiddle(1.5, 2.0, 3.0).
Is new ArrayList<>() { … } legal?
Yes, since Java 9, as long as the inferred type argument is denotable. Before Java 9, the diamond couldn't be used with anonymous classes.
In class Box<T> { <R> Box<R> map(Function<T, R> f) { … } }, which type variables belong to the class and which to the method?
T is the class's type variable, fixed when a Box<T> is created. R belongs to the method and is inferred separately for each call to map.
Previous: Java Debugging Tips: Practical Techniques Beyond the Debugger
Next: Bounded Type Parameters in Java Generics: extends and Multiple Bounds
Related reading
- Java Generics Inheritance Rules and Wildcards: extends, super and ?
- Java Type Erasure: Raw Types, Translation and Bridge Methods
- Bounded Type Parameters in Java Generics: extends and Multiple Bounds
- Throwing Exceptions and Creating Custom Exception Classes in Java
- Java Local, Anonymous and Static Nested Classes

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.