ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume II
  5. Restrictions
Book 1 · Volume II — Generics, Collections & Type System · Topic 3.3

Restrictions

Generic arrays, instanceof, static members and primitive type arguments

11 min readStage 1 · Foundations14 interview questions
Prerequisites
3.2 Erasure Behavior
Covers
Generic arrays · instanceof · Static members · Primitive type arguments
Related
2.2 Wildcards · B1V1 3.5 Wrapper Classes · 5.2 ArrayList Internals
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

Because type arguments do not exist at run time, any operation that needs them at run time is forbidden or restricted. The compiler rejects such code or marks it with unchecked warnings. Each restriction has a standard workaround.

Operations that erasure forbids
Figure 1 — Operations that erasure forbids

2Why It Exists

The restrictions are the other side of erasure (3.1). Some Java operations need a complete type at run time: creating an object or an array, testing instanceof, catching an exception. Erasure removes exactly the information they would need, so the language had two options: let such code compile and behave unpredictably, or reject it. Java rejects it, or allows it only with an unchecked warning that transfers the responsibility to the programmer.

Each restriction therefore protects the guarantee of 1.3: code that compiles without unchecked warnings cannot fail at a compiler-inserted cast. Knowing why a restriction exists makes the workaround obvious: if the code needs the type at run time, someone must supply it, as a Class<T>, a Supplier<T>, an array constructor or a primitive-specialised API.

3Core Concepts

Generic arrays

Arrays check their element type at run time on every store (array covariance, B1V1 3.2). That check needs a reifiable element type. new T[n] is impossible because T is unknown, and new List<String>[n] is forbidden because the array would only know it holds List, so the store check could not prevent heap pollution. Arrays of unbounded wildcard types (new List<?>[n]) are allowed because List<?> is reifiable.

Why generic array creation would be unsafe, and the alternatives
Figure 2 — Why generic array creation would be unsafe, and the alternatives

Generic varargs are a related case: a T... parameter creates a generic array implicitly, producing "possible heap pollution" warnings. @SafeVarargs (on static, final or private methods) asserts that the method does not store into or expose the array unsafely — List.of(E...) and Arrays.asList(T...) are annotated this way.

instanceof

obj instanceof List<String> is illegal because the run-time check cannot see String. Allowed forms test only reifiable types: obj instanceof List<?>, or a pattern such as obj instanceof List<?> list. Since Java 16 a type pattern with type arguments is permitted when the compiler can prove it is safe from the static type — for example, when obj is declared as Collection<String>, obj instanceof List<String> l is fine. Casts to parameterised types, such as (List<String>) obj, compile but are unchecked.

Which instanceof forms are allowed
Figure 3 — Which instanceof forms are allowed

Static members

A class's type parameters cannot be used in static fields, static methods or static initialisers. There is only one static field for all parameterisations — Box<String> and Box<Integer> share Box's statics — so static T defaultValue would have no consistent meaning. Static generic methods declare their own type parameters instead: static <T> Box<T> of(T value).

Primitive type arguments

Type arguments must be reference types: List<int> does not compile, and List<Integer> boxes every element (B1V1 3.5). The JDK compensates with primitive-specialised types — IntStream, OptionalInt, IntFunction, ToIntFunction — and third-party libraries offer primitive collections. Project Valhalla aims to let generics work efficiently over value types; it is not part of Java 25.

Primitive type arguments today and in the future
Figure 4 — Primitive type arguments today and in the future

4How It Works Internally

The rules follow from one definition in the JLS. A type is reifiable when its run-time representation contains all of its information: primitives, non-generic classes, raw types, parameterised types whose arguments are all unbounded wildcards such as List<?>, and arrays of reifiable types (Figure 5). An operation that the JVM performs with a run-time type is allowed only for reifiable types, or, where the compiler can prove the result, with an unchecked warning or a statically safe pattern.

Run-time operations need reifiable types
Figure 5 — Run-time operations need reifiable types

Arrays show the mechanism most clearly. Every array object records its component type, and the aastore instruction checks each store against it, which is how ArrayStoreException arises. An array created as new Object[n] and cast to T[] has component type Object: stores of any object succeed, and the problem appears only when the array reaches code that expects, say, a String[], where javac inserted a checkcast (Example 2). Array.newInstance(type, n) avoids it by creating an array whose component type really is type.

The other restrictions have the same root. instanceof and catch compile to instructions that test a class, so a type variable or type argument has nothing to test; this is also why a generic class cannot extend Throwable. Static members belong to the single Class object shared by all parameterisations. And type arguments must be references because erased code stores every T in a slot of type Object.

5APIs / Features / Syntax

Each restriction has a standard workaround in the JDK:

RestrictionWorkaroundJDK examples
new T()Ask for a Supplier<T> or a Class<T>Collectors.toCollection(ArrayList::new)
new T[n]Object[] inside the class; IntFunction<T[]> or Class<T> for arrays that leave itArrayList (Object[] elementData), Collection.toArray(IntFunction), Array.newInstance
instanceof List<String>instanceof List<?>, a statically safe pattern (Java 16+), or Class.isInstanceClass.cast and Class.isInstance
T in static membersA static generic method with its own type parameterList.of, Map.entry, Optional.empty
List<int>Primitive specialisationsIntStream, OptionalInt, IntFunction, ToIntFunction
Generic varargs@SafeVarargs on static, final or private methods and constructorsList.of(E...), Arrays.asList, EnumSet.of

6Practical Examples

Example 1 — Workarounds for each restriction

Problem. Each restriction of section 3 appears in ordinary code. The box shows the standard idiom for each one.

JAVAWorkarounds for each restriction
// Generic array inside a class: the standard (unchecked, but encapsulated) idiom
public class RingBuffer<T> {
    private final T[] items;
    @SuppressWarnings("unchecked")  // safe: array never escapes as T[]
    public RingBuffer(int capacity) { items = (T[]) new Object[capacity]; }
}

// When the element type must be real at run time: pass Class<T>
public static <T> T[] newArray(Class<T> type, int n) {
    @SuppressWarnings("unchecked")
    T[] a = (T[]) java.lang.reflect.Array.newInstance(type, n);
    return a;
}
String[] names = list.toArray(String[]::new);      // JDK's typed conversion

// instanceof
Object o = List.of("a");
if (o instanceof List<?> l) System.out.println(l.size());

// Static factory with its own type parameter
public final class Box<T> {
    private static int created;                    // shared by all Box<X>
    public static <T> Box<T> of(T value) { created++; return new Box<>(value); }
    private final T value;
    private Box(T value) { this.value = value; }
}

// Primitive specialisation
int total = orders.stream().mapToInt(Order::quantity).sum();   // no boxing

Why it works. RingBuffer keeps an Object[] typed as T[], which is safe because the array never leaves the object. newArray builds a real T[] from a Class<T>, and toArray(String[]::new) lets the caller supply the array constructor. instanceof List<?> tests only what the JVM can see. Box.of declares its own T, while the static counter is shared by every Box<X>. mapToInt switches to an IntStream, so the sum is computed on int values without boxing.

Example 2 — Mini program: a ring buffer with typed exports

Problem. A service keeps the last few events in a fixed-size ring buffer and must hand them to callers as a list or as an array of the right type. The obvious shortcut, returning the internal array, compiles and fails.

JAVATypedRing.java
public class TypedRing<T> {
    private final T[] items;                     // really an Object[]
    private int head, size;
 
    @SuppressWarnings("unchecked")               // safe: never escapes as T[]
    public TypedRing(int capacity) { items = (T[]) new Object[capacity]; }
 
    public void add(T item) {                // overwrites the oldest when full
        items[(head + size) % items.length] = item;
        if (size < items.length) size++; else head = (head + 1) % items.length;
    }
 
    public List<T> toList() {                    // the safe default export
        List<T> out = new ArrayList<>(size);
        for (int i = 0; i < size; i++)
            out.add(items[(head + i) % items.length]);
        return out;
    }
 
    // the caller supplies the array constructor, so the type is real
    public T[] toArray(IntFunction<T[]> newArray) {
        return toList().toArray(newArray.apply(size));
    }
 
    public T[] leakArray() { return items; } // bug: an Object[] as T[]
 
    public static void main(String[] args) {
        TypedRing<String> recent = new TypedRing<>(3);
        for (String s : List.of("a", "b", "c", "d")) recent.add(s);
        System.out.println("list:  " + recent.toList());
        String[] copy = recent.toArray(String[]::new);
        System.out.println("array: " + copy.getClass().getSimpleName() + " "
                + Arrays.toString(copy));
        try {
            String[] leaked = recent.leakArray();  // checkcast String[] fails
            System.out.println(leaked.length);
        } catch (ClassCastException e) {
            System.out.println("leak:  " + e.getMessage().split(" \\(")[0]);
        }
    }
}
OUTPUT
list:  [b, c, d]
array: String[] [b, c, d]
leak:  class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String;
The internal Object[] is safe inside the class and fails when it leaves
Figure 6 — The internal Object[] is safe inside the class and fails when it leaves

Why it behaves this way. Inside TypedRing<String> the field items has the static type T[], but the object is an Object[], and the erased code never notices. toList() copies the elements, and toArray(String[]::new) asks the caller for an array whose component type really is String. leakArray() returns the Object[] itself; in main javac inserts a checkcast String[] where the result is assigned, and that cast fails (Figure 6). The unchecked warning in the constructor was suppressed with a promise, "never escapes as T[]", that leakArray breaks.

Example 3 — instanceof with generic types since Java 16

Problem. Code that receives an Object must test what kind of collection it got, and code that receives a Collection<String> sometimes wants the List operations. The program shows the forms that compile.

JAVAPatternForms.java
public class PatternForms {
    static String describe(Object o) {
        if (o instanceof Map<?, ?> m) return "map of " + m.size();
        if (o instanceof List<?> l && !l.isEmpty()
                && l.getFirst() instanceof String s)
            return "list starting with \"" + s + "\"";
        if (o instanceof Collection<?> c) return "collection of " + c.size();
        return "something else";
    }
 
    static int firstLength(Collection<String> names) {
        // allowed since Java 16: this cast is provably safe
        if (names instanceof List<String> list) return list.getFirst().length();
        return -1;
    }
 
    public static void main(String[] args) {
        System.out.println(describe(List.of("ann", "bob")));
        System.out.println(describe(Set.of(1, 2, 3)));
        System.out.println(describe(Map.of("k", 1)));
        System.out.println(firstLength(List.of("christopher")) + " "
                + firstLength(Set.of("x")));
        // o instanceof List<String> l   // error: not provably safe
    }
}
OUTPUT
list starting with "ann"
collection of 3
map of 1
11 -1

Why it behaves this way. On an Object, only reifiable types can be tested, so describe uses Map<?, ?>, List<?> and Collection<?>, and checks an element's type separately with a nested pattern. In firstLength the static type is already Collection<String>, so if the object is a List it can only be a List<String>; since Java 16 the compiler accepts that pattern because the cast is provably safe. The commented line is the case it still rejects.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
Returning an internal (T[]) new Object[n] to callers as T[]Callers that expect a String[] get a ClassCastException at an inserted cast (Example 2)Keep such arrays private; return a List or take an IntFunction<T[]>
@SafeVarargs on a method that stores or returns its varargs arrayThe warning is gone but the heap pollution is not; callers receive an Object[] as T[]Annotate only methods that just read the array (1.3)
Unchecked casts to List<String> from Object without validating elementsHeap pollution: the failure appears later, at a readValidate each element, or copy into a new list with Class.cast
Boxed streams for large numeric work (Stream<Integer>.reduce)An Integer object per value: more memory, more GC, slowermapToInt, IntStream, primitive arrays
Comparing boxed values with ==Works for small values from the Integer cache (-128 to 127) and fails above itUse equals, or unbox to int first
Designing a generic exception, or catching TDoes not compile: catch needs a reifiable classWrap the payload: a non-generic exception with a typed field or cause

8Performance & Production Considerations

The restriction with a measurable cost is primitives. A List<Integer> stores a reference per element to a separate Integer object of about 16 bytes, so a million values take roughly 20 MB on a typical 64-bit JVM with compressed references, against 4 MB for an int[], and every read and write boxes or unboxes. Values from -128 to 127 come from the Integer cache and are shared, which also explains why == on boxed values seems to work in small tests.

The workarounds are cheap. Array.newInstance is a reflective call but costs little next to the array it allocates, and Class.cast is a type check the JIT handles well. In production, the restrictions show up mostly as ClassCastException messages with array types, such as [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String;, which almost always mean that an internal generic array has escaped, and as GC pressure from boxed collections, which a heap histogram (jcmd <pid> GC.class_histogram) reveals as millions of java.lang.Integer or java.lang.Long instances.

9Architecture & Design Considerations

The restrictions push APIs toward collections instead of arrays in public signatures, explicit Class<T> or type-token parameters where run-time types matter, and primitive-specialised APIs for performance-critical numeric paths. Designing with these in mind avoids unchecked casts leaking across module boundaries.

10Interview Questions & Answers

Q1L1 · BasicConcept

Why can't you write new T() in a generic class?

T is erased, so at run time the class does not know which constructor to call. Pass a Supplier<T> or Class<T> to create instances. A Supplier<T> such as Order::new is checked by the compiler and needs no reflection, so it is usually the better choice.

Q2L2 · IntermediateInternals

Why is new List<String>[10] not allowed?

Arrays enforce their element type at run time, but they would know only List, not List<String>. A List<Integer> could then be stored through an Object[] alias without an ArrayStoreException, causing heap pollution. Arrays of List<?> are allowed.

Q3L2 · IntermediateConcept

Can you use a class's type parameter in a static method?

No. Static members are shared by all parameterisations, so the class's T has no meaning there. A static method can declare its own type parameter. This is how List.of and Optional.empty work.

Q4L3 · Senior EngineerTricky

Why can't you write obj instanceof List<String>?

The run-time check cannot see type arguments. You can test instanceof List<?>, or use a type pattern with type arguments only when the compiler can prove its safety from obj's static type. For example, for a Collection<String> names, names instanceof List<String> list compiles since Java 16 (Example 3).

Q5L3 · Senior EngineerInternals

What does @SafeVarargs promise?

That the generic varargs method does not perform unsafe operations on the implicitly created array, such as storing incompatible values or exposing it. It suppresses heap-pollution warnings at call sites and is allowed on static, final and private methods and constructors. If the method breaks that promise, the annotation hides a real heap-pollution bug (1.3).

Q6L3 · Senior EngineerInternals

How does ArrayList store elements if it cannot create a T[]?

It uses an Object[] internally and casts elements to E when returning them. The array never escapes as E[], so the unchecked cast is safe; toArray(T[]) and toArray(IntFunction) create correctly typed arrays for callers.

Q7L4 · Technical ArchitectDesign

How do these restrictions influence public API design?

Prefer List over arrays in signatures; accept Class<T>, Supplier<T> or type tokens when run-time type knowledge is needed; provide primitive-specialised methods for hot numeric paths; and keep unchecked operations encapsulated so callers never see them.

Q8L1 · BasicConcept

What is a reifiable type?

A type whose run-time representation contains all of its information, so the JVM can check it. Primitives, non-generic types such as String, raw types such as List, unbounded wildcard types such as List<?>, and arrays of these are reifiable; List<String>, T and List<? extends Number> are not (Figure 5). Array creation, instanceof and catch need reifiable types.

Q9L2 · IntermediateCode

What does this program print?

JAVABoxingQuiz.java
public class BoxingQuiz {
    public static void main(String[] args) {
        List<Integer> xs = List.of(127, 127, 128, 128);
        System.out.println(xs.get(0) == xs.get(1));
        System.out.println(xs.get(2) == xs.get(3));
        System.out.println(xs.get(2).equals(xs.get(3)));
        int sum = 0;
        for (int x : xs) sum += x;                 // unboxing on every read
        System.out.println(sum);
    }
}

It prints true, then false, then true, then 510. A List<Integer> holds Integer objects. Autoboxing uses Integer.valueOf, which returns cached objects for -128 to 127, so the two 127s are the same object and == is true; the two 128s are different objects, so == is false while equals is true. The loop unboxes each element to add it.

Q10L3 · Senior EngineerCode

A generic method returns T[]. What does this program print?

JAVAArrayEscapeQuiz.java
public class ArrayEscapeQuiz {
    @SuppressWarnings("unchecked")
    static <T> T[] firstTwo(List<T> items) {
        Object[] a = { items.get(0), items.get(1) };
        return (T[]) a;                        // unchecked: an Object[]
    }
 
    public static void main(String[] args) {
        List<String> names = List.of("ann", "bob", "cy");
        Object[] ok = firstTwo(names);             // no cast to String[] needed
        System.out.println(ok.length + " " + ok.getClass().getSimpleName());
        try {
            String[] bad = firstTwo(names);    // inserted checkcast String[]
            System.out.println(bad[0]);
        } catch (ClassCastException e) {
            System.out.println("ClassCastException");
        }
    }
}

It prints 2 Object[], then ClassCastException. firstTwo creates an Object[] and returns it as T[] with an unchecked cast. Assigned to an Object[], no cast is needed and everything works. Assigned to a String[], javac inserts checkcast String[], which fails because the array's real component type is Object. A safe version takes an IntFunction<T[]> from the caller.

Q11L3 · Senior EngineerTricky

Why can a class not be declared as class ValidationException<T> extends Exception?

A generic class may not extend Throwable, directly or indirectly. Exceptions are matched by catch clauses at run time using the exception's class, and after erasure ValidationException<Order> and ValidationException<Invoice> would be the same class, so catch (ValidationException<Order> e) could never work as written. Use a non-generic exception that carries the typed information in a field, or a generic result type such as Result<T> instead of an exception.

Q12L3 · Senior EngineerScenario

Production logs show "class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String;" from a reporting endpoint after a refactoring introduced a generic utility. How do you investigate and fix it?

The message names array types, so a value created as Object[] reached code that expects a String[]. Look in the new utility for a (T[]) new Object[n] or a toArray() result cast to T[] that is returned to callers; the stack trace points at the caller's inserted cast, not at the creation. Fix the API rather than the caller: return a List<T>, or take an IntFunction<T[]> or Class<T> and create the array with the real component type (Example 2). Add a test that assigns the result to a concrete array type.

Q13L4 · Technical ArchitectTrade-off

Should a public API return arrays or lists?

Lists, in most cases. A List<T> works with generics, can be immutable (List.copyOf), and hides how the data is stored; a generic method cannot safely create a T[] without help, and arrays are mutable, covariant and checked only at run time. Arrays still make sense for primitive data, where int[] avoids boxing, for performance-critical internal code and for varargs. When an array is needed, let the caller supply the constructor, as Collection.toArray(IntFunction) does.

Q14L5 · Solution ArchitectDesign

Your platform processes large numeric time series. How do you design its core APIs given that generics cannot take primitives?

Keep the generic, boxed APIs for flexible, low-volume paths, and give the hot paths primitive-specialised types: double[] or LongBuffer-backed series classes, DoubleStream operations and primitive functional interfaces such as DoubleUnaryOperator, or a primitive collections library. Hide the representation behind domain types such as TimeSeries, so the implementation can change when Valhalla's value types and specialised generics arrive without breaking callers. Measure with realistic volumes: memory per point and GC time decide where specialisation pays off.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • No generic array creation; use collections, Object[] internally, or Array.newInstance with Class<T>.
  • instanceof works only with reifiable types, apart from statically safe patterns.
  • Class type parameters are unavailable in static members.
  • Type arguments must be reference types; use primitive specialisations for performance.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.