Java Generics Restrictions and Limitations: What You Can't Do with Type Parameters
The complete list of Java generics restrictions and their workarounds: no primitives, instanceof only on raw types, no generic arrays, @SafeVarargs, new T() and new T[], static context, generic exceptions, sneaky throws, erasure clashes and record pattern exhaustiveness.
kvi5hnuCode Sprout team member14 min readOn this page
Java generics are powerful, but they come with a list of things you simply can't do. Almost every item on that list is a consequence of type erasure: at run time, there are no type arguments, only raw classes. This article goes through the restrictions one by one, explains why each exists, and shows the standard workaround. When you hit one of these compiler errors, you'll know what's happening and how to fix it.
![Table of nine generics restrictions, such as Pair<double>, new T() and new T[n], each with its workaround, such as Pair<Double>, a Supplier or an IntFunction array constructor](https://code-sprout-content.laxmi.solutions/asset/2026/11/hddbgb7loo2dxzij.png)
1. Type parameters can't be primitive types
You can't substitute a primitive type for a type parameter. There's no Pair<double>, only Pair<Double>. The reason is erasure: after erasure, Pair has fields of type Object, which can't hold double values.
It's an annoyance, but consistent with the separate status of primitive types in Java. It isn't fatal: there are only eight primitive types, and when wrapper types aren't acceptable, for performance or memory reasons, you can write specialized classes and methods. The JDK does this itself with IntStream, IntFunction, OptionalInt and friends.
2. Run-time type inquiry only works with raw types
Objects in the virtual machine always have a specific, non-generic type. So any type inquiry can only check the raw type:
if (a instanceof Pair<String>) // ERROR
if (a instanceof Pair<T>) // ERROR
Pair<String> p = (Pair<String>) a; // warning: unchecked cast
The first two could only test whether a is some Pair, so the compiler rejects them, unless the static type already guarantees the type argument. Casts compile with an "unchecked" warning to remind you of the risk. Use the wildcard form instead, which is honest about what's checked:
if (a instanceof Pair<?> p) . . .
In the same spirit, getClass always returns the raw type:
Pair<String> stringPair = . . .;
Pair<Employee> employeePair = . . .;
if (stringPair.getClass() == employeePair.getClass()) // they are equal
The comparison is true: both calls return Pair.class.
3. You can't create arrays of parameterized types
This is illegal:
var table = new Pair<String>[10]; // ERROR
What's wrong with it? After erasure, the type of table would be Pair[], which converts to Object[]:
Object[] objarray = table;
Arrays remember their component type and throw an ArrayStoreException when you store the wrong kind of element:
objarray[0] = "Hello"; // ERROR: component type is Pair
But erasure makes this check useless for generic types. The assignment
objarray[0] = new Pair<Employee>();
would pass the array store check, since it is a Pair, and still be a type error. That's why arrays of parameterized types are outlawed.
Only creating them is illegal. You can declare a variable of type Pair<String>[], but you can't initialize it with new Pair<String>[10].
Workaround: to collect parameterized objects, use a list. ArrayList<Pair<String>> is safe and efficient.
4. Varargs warnings and @SafeVarargs
A related issue arises with generic variable-argument methods. Consider:
public static <E> void addAll(Collection<E> coll, E... elements) {
for (E element : elements) coll.add(element);
}
The parameter elements is really an array holding the arguments. Now call it:
Collection<Pair<String>> table = . . .;
Pair<String> pair1 = . . .;
Pair<String> pair2 = . . .;
addAll(table, pair1, pair2);
To make that call, the VM must create an array of Pair<String>, which is against the rules. The rules are relaxed for this case: instead of an error, you get a warning at the call site. You could suppress it with @SuppressWarnings("unchecked") in every method that calls addAll, but that burdens all callers. There's also a warning about "possible heap pollution" at the declaration.
To get rid of both, annotate the method itself:
@SafeVarargs
public static <E> void addAll(Collection<E> coll, E... elements)
Now the method can be called with generic types without warnings. With the annotation, you promise that the method doesn't write into the parameter array and doesn't pass the array to code that might. @SafeVarargs is allowed only on constructors and on methods that are static, final or (since Java 9) private. Any other method could be overridden, and the promise would be meaningless. Library methods such as List.of, Set.of, Arrays.asList and Stream.of carry this annotation.
5. Generic varargs don't spread primitive arrays
You can pass an array to a varargs parameter. The call behaves as if the elements had been spread out:
Collection<String> strings = . . .;
String[] moreStrings = { "Mary", "had", "a", "little", "lamb" };
addAll(strings, moreStrings); // OK, same as addAll(strings, "Mary", "had", ...)
(The elements aren't really spread. Individually listed arguments are gathered into an array, and an array you supply is passed directly.)
Now try numbers:
Collection<Integer> numbers = . . .;
int[] moreNumbers = { 11, 12, 13, 14, 15 };
addAll(numbers, moreNumbers); // ERROR
That fails. No E makes it work, because an int[] can't be converted to an Integer[]. More insidious is List.of, declared as static <E> List<E> of(E... elements):
List.of(moreStrings)gives a list of five strings.List.of(moreNumbers)gives aList<int[]>with one element, the whole array.Ecan't beint, so it matchesint[]instead.
To get a list of numbers from an int[], use Arrays.stream(moreNumbers).boxed().toList().
6. You can't instantiate type variables
You can't write new T(...). This Pair<T> constructor is illegal:
public Pair() { first = new T(); second = new T(); } // ERROR
After erasure, T is Object, and you certainly don't want new Object().
Best workaround: make the caller provide a constructor expression, a Supplier<T>:
public static <T> Pair<T> makePair(Supplier<T> constr) {
return new Pair<>(constr.get(), constr.get());
}
Pair<String> p = Pair.makePair(String::new);
Traditional workaround: reflection. You can't write T.class.getConstructor().newInstance(), because T.class isn't legal: it would erase to Object.class. Instead, design the API so the caller hands you a Class object:
public static <T> Pair<T> makePair(Class<T> cl) throws ReflectiveOperationException {
Constructor<T> constr = cl.getConstructor();
return new Pair<>(constr.newInstance(), constr.newInstance());
}
Pair<String> p = Pair.makePair(String.class);
The method declares ReflectiveOperationException because the class might lack a no-argument constructor. Class is itself generic: String.class is the only instance of Class<String>, so makePair can infer the type of pair it makes.
7. You can't construct a generic array
Just as you can't create a single T, you can't create a T[]. The reasons differ slightly: an array starts out filled with nulls, which seems harmless, but an array also carries its component type, and that type would be erased:
public static <T extends Comparable<? super T>> T[] minmax(T... a) {
T[] mm = new T[2]; // ERROR
. . .
}
Erasure would always make this a Comparable[2].
If the array is only a private field of a class, you can declare it with the erased type and cast on the way out. That's how ArrayList is implemented:
public class ArrayList<E> {
private Object[] elements;
. . .
@SuppressWarnings("unchecked") public E get(int n) { return (E) elements[n]; }
public void set(int n, E e) { elements[n] = e; } // no cast needed
}
That doesn't work when you return a T[]. Lying about the array's type causes a run-time error:
public static <T extends Comparable<? super T>> T[] minmax(T... a) {
var result = new Comparable[2]; // array of erased type
. . .
return (T[]) result; // compiles with warning
}
String[] names = ArrayAlg.minmax("Tom", "Dick", "Omar"); compiles without any warning, but a ClassCastException occurs when the returned Comparable[] is cast to String[].
Best workaround: ask the caller for an array constructor expression:
String[] names = ArrayAlg.minmax(String[]::new, "Tom", "Dick", "Omar");
String[]::new is a function that, given a length, makes a String array of that length. The method uses it:
public static <T extends Comparable<? super T>> T[] minmax(IntFunction<T[]> constr, T... a) {
T[] result = constr.apply(2);
. . .
}
Old-fashioned workaround: reflection with Array.newInstance:
@SuppressWarnings("unchecked")
var result = (T[]) Array.newInstance(a.getClass().getComponentType(), 2);
ArrayList.toArray faces the same problem: it must produce a T[] but doesn't know the component type. So it comes in variants:
Object[] toArray()
<T> T[] toArray(T[] result) // uses result if large enough, else creates one of its type
default <T> T[] toArray(IntFunction<T[]> generator) // Java 11: list.toArray(String[]::new)
8. Type variables aren't valid in static contexts of generic classes
You can't use a class's type variables in static fields or methods. This clever idea doesn't work:
public class Singleton<T> {
private static T singleInstance; // ERROR
public static T getSingleInstance() { // ERROR
if (singleInstance == null) construct new instance of T
return singleInstance;
}
}
If it could, a program could declare a Singleton<Random> to share a random number generator and a Singleton<JFileChooser> to share a file chooser. But after erasure there's only one Singleton class, with only one singleInstance field. So static members with class type variables are outlawed. A static generic method with its own type variable, static <U> U foo(...), is fine.
9. You can't throw or catch instances of a generic class
You can neither throw nor catch objects of a generic class. In fact, a generic class can't even extend Throwable:
public class Problem<T> extends Exception { /* . . . */ } // ERROR: can't extend Throwable
A catch clause can't use a type variable either:
public static <T, E extends Exception> void doWork(CheckedConsumer<T, E> c, T t) {
try {
c.accept(t);
} catch (E e) { // ERROR: can't catch type variable
logger.log(ERROR, ". . .", e);
}
}
The catch would need a run-time type test against E, which is erased.
Using type variables in exception specifications is fine, though:
interface CheckedConsumer<T, E extends Exception> {
void accept(T t) throws E;
}
A method can then declare throws E and let the compiler infer exactly which checked exception, if any, a lambda throws. The demo's forEachChecked does this.
10. You can defeat checked exception checking
A bedrock principle of Java exception handling is that every checked exception needs a handler. Generics can be used to get around that. The key ingredient is this method:
@SuppressWarnings("unchecked")
static <T extends Throwable> void throwAs(Throwable t) throws T {
throw (T) t;
}
Suppose it's in an interface Task. If you have a checked exception e and call
Task.<RuntimeException>throwAs(e);
the compiler believes e has become an unchecked exception. The cast to T is erased to a cast to Throwable, so nothing stops the exception at run time. This turns every exception into one the compiler considers unchecked:
try {
do work
} catch (Throwable t) {
Task.<RuntimeException>throwAs(t);
}
Here's a use. A Runnable's run method can't throw checked exceptions. This adapter turns a Task, whose run may throw anything, into a Runnable:
interface Task {
void run() throws Exception;
@SuppressWarnings("unchecked")
static <T extends Throwable> void throwAs(Throwable t) throws T {
throw (T) t;
}
static Runnable asRunnable(Task task) {
return () -> {
try {
task.run();
} catch (Exception e) {
Task.<RuntimeException>throwAs(e);
}
};
}
}
This thread throws a checked exception from run:
var thread = new Thread(Task.asRunnable(() -> {
Thread.sleep(1000);
System.out.println("Hello, World!");
throw new Exception("Check this out!");
}));
thread.start();
Thread.sleep declares InterruptedException, and we no longer have to catch it. The checked Exception escapes run without wrapping, and the program prints a stack trace. Normally you'd have to catch it and wrap it in an unchecked exception.
Generics, erasure and @SuppressWarnings together have defeated an essential part of the type system. This "sneaky throw" technique appears in some libraries, such as Lombok's @SneakyThrows. Use it rarely and knowingly: callers can't catch the exception by its checked type unless they catch a supertype like Exception, because the compiler insists the try block can't throw it.
11. Beware of clashes after erasure
After erasure, two methods that looked different in the source can end up with the same signature. The compiler rejects any declaration that would cause such a collision. A common way to trip over this is to write an equals that takes the type parameter:
public class Cell<T> {
private T value;
public boolean equals(T other) { return value.equals(other); } // ERROR
}
In source form, equals(T) looks like an overload of Object.equals(Object). But T erases to Object, so in the class file both would be boolean equals(Object), and neither one actually overrides the other. javac says so directly: name clash: equals(T) in Cell and equals(Object) in Object have the same erasure, yet neither overrides the other. The fix is to choose a different name, such as holds(T), or to write a real equals(Object) override.
A related restriction from the language specification: a class (or a type variable) can't be a subtype of two different parameterizations of the same generic interface. This hierarchy is therefore illegal:
class Ticket implements Comparable<Ticket> { . . . }
class VipTicket extends Ticket implements Comparable<VipTicket> { . . . } // ERROR
The compiler reports Comparable cannot be inherited with different arguments: <VipTicket> and <Ticket>. Oddly, the raw form implements Comparable would compile, which hints that the reason lies in the generated code. Each Comparable<X> that a class implements requires a bridge method
public int compareTo(Object other) { return compareTo((X) other); }
and VipTicket would need two of them with the identical signature compareTo(Object), one casting to Ticket and one to VipTicket. A class file can't hold both.
12. Type inference in generic record patterns is limited
With sealed hierarchies and record patterns, the compiler can check switch exhaustiveness, even with generics. Consider a small hierarchy of JSON values:
sealed interface JSONPrimitive<T> { }
record JSONNumber(double value) implements JSONPrimitive<Double> { }
record JSONBoolean(boolean value) implements JSONPrimitive<Boolean> { }
record JSONString(String value) implements JSONPrimitive<String> { }
This switch is exhaustive. The compiler knows there are exactly three implementations:
public static <T> double toNumber(JSONPrimitive<T> v) {
return switch (v) {
case JSONNumber(var n) -> n;
case JSONBoolean(var b) -> b ? 1 : 0;
case JSONString(var s) -> {
try {
yield Double.parseDouble(s);
} catch (NumberFormatException ex) {
yield Double.NaN;
}
}
};
}
Now add the values in a pair:
record Pair<T>(T first, T second) {
public static <U> Pair<U> of(U first, U second) { return new Pair<>(first, second); }
}
public static Object sum(Pair<? extends JSONPrimitive<?>> pair) {
return switch (pair) {
case Pair(JSONNumber(var left), JSONNumber(var right)) -> left + right;
case Pair(JSONBoolean(var left), JSONBoolean(var right)) -> left || right;
case Pair(JSONString(var left), JSONString(var right)) -> left + right;
// ERROR: not exhaustive
};
}
That's correctly rejected: someone could call sum(Pair.of(new JSONNumber(42), new JSONString("Fred"))). You could add the six mixed combinations and throw an exception in each, but that's a run-time check. To reject mixed pairs at compile time, tie the components to one type:
public static <T extends JSONPrimitive<U>, U> Object sum(Pair<T> pair) {
return switch (pair) {
case Pair(JSONNumber(var left), JSONNumber(var right)) -> left + right;
case Pair(JSONBoolean(var left), JSONBoolean(var right)) -> left || right;
case Pair(JSONString(var left), JSONString(var right)) -> left + right;
default -> throw new AssertionError(); // still needed
};
}
The mixed call no longer compiles, since no T and U match. Unfortunately, the default clause is still required. In theory there's enough information to prove that both components have the same type, but Java's type system can't prove it. Explicit type arguments in the patterns, such as case Pair<JSONNumber>(JSONNumber(var l), JSONNumber(var r)), don't help either: the compiler rejects them as unsafe casts from Pair<T>.
A complete example
The program demonstrates most of the restrictions and their workarounds. The lines that wouldn't compile are left out or commented.
import java.lang.reflect.Array;
import java.util.*;
import java.util.function.*;
public class Solution {
public static void main(String[] args) throws Exception {
// 1. no primitive type arguments: Pair<Double>, not Pair<double>
var p = new Pair<Double>(1.5, 2.5);
double sum = p.getFirst() + p.getSecond(); // auto-unboxing
System.out.println("sum = " + sum);
// 2. run-time type inquiry sees only the raw type
Object obj = new Pair<String>("a", "b");
System.out.println("instanceof Pair<?>: " + (obj instanceof Pair<?>));
System.out.println("same class: " + (new Pair<String>("x", "y").getClass() == new Pair<Integer>(1, 2).getClass()));
// 3. no arrays of parameterized types; use a list instead
List<Pair<String>> table = new ArrayList<>();
table.add(new Pair<>("k1", "v1"));
System.out.println("table: " + table);
@SuppressWarnings("unchecked")
Pair<String>[] unsafe = (Pair<String>[]) new Pair<?>[1]; // compiles, but...
Object[] objarray = unsafe;
objarray[0] = new Pair<Integer>(1, 2); // ...no ArrayStoreException
try {
String s = unsafe[0].getFirst(); // the failure shows up here
System.out.println(s);
} catch (ClassCastException e) {
System.out.println("ClassCastException far from the real mistake");
}
// 4. generic varargs: @SafeVarargs silences the warnings
Collection<Pair<String>> pairs = new ArrayList<>();
addAll(pairs, new Pair<>("a", "b"), new Pair<>("c", "d"));
System.out.println("added " + pairs.size() + " pairs");
// 5. generic varargs don't spread primitive arrays
String[] moreStrings = { "Mary", "had", "a", "little", "lamb" };
int[] moreNumbers = { 11, 12, 13, 14, 15 };
System.out.println("List.of(String[]) has " + List.of(moreStrings).size() + " elements");
System.out.println("List.of(int[]) has " + List.of(moreNumbers).size() + " element: a " + List.of(moreNumbers).get(0).getClass().getSimpleName());
// 6. no new T(): ask for a constructor reference, or a Class object
Pair<StringBuilder> sbs = Pair.makePair(StringBuilder::new);
Pair<String> strings = Pair.makePair(String.class);
System.out.println("made: " + sbs.getFirst().getClass().getSimpleName() + ", " + "\"" + strings.getFirst() + "\"");
// 7. no new T[n]: ask for an array constructor, or use Array.newInstance
String[] mm = ArrayAlg.minmax(String[]::new, "Tom", "Dick", "Omar");
System.out.println("minmax: " + Arrays.toString(mm));
String[] mm2 = ArrayAlg.minmaxReflect("Tom", "Dick", "Omar");
System.out.println("minmax via reflection: " + Arrays.toString(mm2));
try {
String[] broken = ArrayAlg.minmaxBroken("Tom", "Dick", "Omar");
System.out.println(broken.length);
} catch (ClassCastException e) {
System.out.println("minmaxBroken: ClassCastException, Comparable[] is not a String[]");
}
var names = new ArrayList<>(List.of("Ada", "Linus"));
String[] a1 = names.toArray(new String[0]);
String[] a2 = names.toArray(String[]::new); // Java 11
System.out.println(a1.length + " " + a2.length + " " + a2.getClass().getSimpleName());
// 9. type variables in throws clauses are fine
try {
forEachChecked(List.of("1", "2", "x"), s -> {
if (!s.chars().allMatch(Character::isDigit)) throw new java.io.IOException("not a number: " + s);
System.out.println("ok " + s);
});
} catch (java.io.IOException e) {
System.out.println("IOException: " + e.getMessage());
}
// 10. the "sneaky throw": a checked exception escapes a Runnable
Runnable r = Task.asRunnable(() -> { throw new Exception("Check this out!"); });
try {
r.run();
} catch (Exception e) {
System.out.println("caught " + e.getClass().getName() + ": " + e.getMessage());
}
// 12. generic record patterns and exhaustiveness
System.out.println(Json.toNumber(new JSONBoolean(true)) + " " + Json.toNumber(new JSONString("2.5")));
System.out.println(Json.sum(Pair2.of(new JSONNumber(40), new JSONNumber(2))));
System.out.println(Json.sum(Pair2.of(new JSONString("Hello, "), new JSONString("World"))));
// Json.sum(Pair2.of(new JSONNumber(42), new JSONString("Fred"))); // won't compile
}
@SafeVarargs
public static <E> void addAll(Collection<E> coll, E... elements) {
for (E element : elements) coll.add(element);
}
public static <T, E extends Exception> void forEachChecked(List<T> list, CheckedConsumer<T, E> action) throws E {
for (T t : list) action.accept(t);
}
}
class Pair<T> {
private final T first;
private final T second;
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
@Override public String toString() { return "(" + first + ", " + second + ")"; }
public static <T> Pair<T> makePair(Supplier<T> constr) {
return new Pair<>(constr.get(), constr.get());
}
public static <T> Pair<T> makePair(Class<T> cl) throws ReflectiveOperationException {
var constr = cl.getConstructor();
return new Pair<>(constr.newInstance(), constr.newInstance());
}
}
class ArrayAlg {
@SafeVarargs
public static <T extends Comparable<? super T>> T[] minmax(IntFunction<T[]> constr, T... a) {
T[] result = constr.apply(2);
T min = a[0], max = a[0];
for (T t : a) {
if (t.compareTo(min) < 0) min = t;
if (t.compareTo(max) > 0) max = t;
}
result[0] = min;
result[1] = max;
return result;
}
@SafeVarargs
public static <T extends Comparable<? super T>> T[] minmaxReflect(T... a) {
@SuppressWarnings("unchecked")
var result = (T[]) Array.newInstance(a.getClass().getComponentType(), 2);
T min = a[0], max = a[0];
for (T t : a) {
if (t.compareTo(min) < 0) min = t;
if (t.compareTo(max) > 0) max = t;
}
result[0] = min;
result[1] = max;
return result;
}
@SafeVarargs
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends Comparable<? super T>> T[] minmaxBroken(T... a) {
var result = new Comparable[2]; // array of the erased type
T min = a[0], max = a[0];
for (T t : a) {
if (t.compareTo(min) < 0) min = t;
if (t.compareTo(max) > 0) max = t;
}
result[0] = min;
result[1] = max;
return (T[]) result; // compiles with a warning, lies about the type
}
}
@FunctionalInterface
interface CheckedConsumer<T, E extends Exception> {
void accept(T t) throws E;
}
interface Task {
void run() throws Exception;
@SuppressWarnings("unchecked")
static <T extends Throwable> void throwAs(Throwable t) throws T {
throw (T) t;
}
static Runnable asRunnable(Task task) {
return () -> {
try {
task.run();
} catch (Exception e) {
Task.<RuntimeException>throwAs(e);
}
};
}
}
sealed interface JSONPrimitive<T> { }
record JSONNumber(double value) implements JSONPrimitive<Double> { }
record JSONBoolean(boolean value) implements JSONPrimitive<Boolean> { }
record JSONString(String value) implements JSONPrimitive<String> { }
record Pair2<T>(T first, T second) {
public static <U> Pair2<U> of(U first, U second) { return new Pair2<>(first, second); }
}
class Json {
public static <T> double toNumber(JSONPrimitive<T> v) {
return switch (v) { // exhaustive: the compiler knows all three implementations
case JSONNumber(var n) -> n;
case JSONBoolean(var b) -> b ? 1 : 0;
case JSONString(var s) -> {
try {
yield Double.parseDouble(s);
} catch (NumberFormatException ex) {
yield Double.NaN;
}
}
};
}
/** Only accepts pairs whose components have the same JSON type. */
public static <T extends JSONPrimitive<U>, U> Object sum(Pair2<T> pair) {
return switch (pair) {
case Pair2(JSONNumber(var left), JSONNumber(var right)) -> left + right;
case Pair2(JSONBoolean(var left), JSONBoolean(var right)) -> left || right;
case Pair2(JSONString(var left), JSONString(var right)) -> left + right;
default -> throw new AssertionError(); // can't happen, but the compiler can't prove it
};
}
}
sum = 4.0
instanceof Pair<?>: true
same class: true
table: [(k1, v1)]
ClassCastException far from the real mistake
added 2 pairs
List.of(String[]) has 5 elements
List.of(int[]) has 1 element: a int[]
made: StringBuilder, ""
minmax: [Dick, Tom]
minmax via reflection: [Dick, Tom]
minmaxBroken: ClassCastException, Comparable[] is not a String[]
2 2 String[]
ok 1
ok 2
IOException: not a number: x
caught java.lang.Exception: Check this out!
1.0 2.5
42.0
Hello, World
Common questions
How do I create a T[] inside a generic method?
Ask the caller for an array constructor: add an IntFunction<T[]> parameter and pass String[]::new. The older alternative is Array.newInstance(componentClass, n) with a cast. For a private field that is never exposed, an Object[] with casts on the way out is fine, which is what ArrayList does.
Why does List.of(intArray) give me a list with one element?
E can't be the primitive int, so the compiler infers E as int[] and treats the whole array as one argument. Use Arrays.stream(intArray).boxed().toList(), or declare the array as Integer[].
When may I put @SafeVarargs on a method?
Only when the method doesn't store anything into the varargs array and doesn't let the array escape, for example by returning it or keeping a reference. It's allowed on constructors and on static, final and private methods, because those can't be overridden.
Is the "sneaky throw" trick safe to use?
It works reliably, because the JVM doesn't check exception declarations. The trouble is for callers: they can't write catch (IOException e) around your call, since the compiler thinks the method can't throw it. Wrapping in an unchecked exception, such as UncheckedIOException, is usually the clearer choice.
Can a generic class extend Exception?
No. class Problem<T> extends Exception is a compile-time error, because catch clauses would need a run-time type test that erasure can't provide. A type variable can still appear in a throws clause, as in <E extends Exception> void run() throws E.
Summary
| Restriction | Reason | Workaround |
|---|---|---|
| No primitive type arguments | Erased fields are Object | Wrapper types, primitive specializations |
instanceof/casts check only raw types | Objects have no type arguments | Pair<?>, checking components |
No new Pair<String>[n] | Array store checks can't see type arguments | ArrayList<Pair<String>> |
| Generic varargs warn | They create generic arrays | @SafeVarargs on static/final/private methods |
Varargs don't spread int[] | E can't be primitive | Arrays.stream(a).boxed() |
No new T() | T erases to its bound | Supplier<T>, Class<T> |
No new T[n] | Array component type is erased | IntFunction<T[]>, Array.newInstance |
No T in static members | One class after erasure | Generic static methods with their own type variables |
No generic Throwable, no catch (E e) | catch needs a run-time type test | Concrete exception classes, throws E |
| No erasure clashes | Methods or bridges would collide | Rename, implement one parameterization |
Practice Questions
Why is new ArrayList<String>[10] illegal but new ArrayList<?>[10] legal?
An array of an unbounded wildcard type is safe: its run-time component type, ArrayList, says everything the static type promises. An ArrayList<String>[] would promise string lists, but the array store check could only verify ArrayList, so the type system would be unsound.
What does List.of(new int[] {1, 2, 3}).size() return, and why?
Ecan't be the primitiveint, so it is inferred asint[], and the whole array becomes the single element of aList<int[]>.
A generic method needs to create a new T. How should you design its signature?
Accept a Supplier<T>, such as String::new, or a Class<T> and use reflection. Prefer the supplier: it is type-checked and needs no exception handling.
Why does a method returning (T[]) new Object[n] fail when called from code that expects a String[]?
The cast to T[] is erased to a cast to Object[] and does nothing at run time. The caller's code contains a cast to String[], and that fails with a ClassCastException because the actual array is an Object[].
On which kinds of methods can @SafeVarargs be used, and why the restriction?
Constructors, and static, final or private methods, because those can't be overridden. An overriding method could break the promise that the varargs array is used safely.
Why can't VipTicket implement Comparable<VipTicket> when its superclass Ticket already implements Comparable<Ticket>?
Each parameterization requires a bridge method compareTo(Object) casting to its own type. VipTicket would need two bridge methods with the same signature, which is impossible, so the compiler rejects the declaration.
How does throwAs make the compiler treat a checked exception as unchecked?
Calling Task.<RuntimeException>throwAs(e) makes the method's throws T clause read throws RuntimeException, so the compiler requires no handler. At run time, the cast (T) t erases to (Throwable) t and has no effect, so the original checked exception is thrown unchanged.
Previous: Java Generics Inheritance Rules and Wildcards: extends, super and ?
Next: Java Reflection and Generics: Class<T>, Type Tokens and the Type Interface
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
- Java Generics: Generic Classes and Generic Methods
- Java Reflection: Invoking Methods and Writing Generic Array Code

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.