Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Heap pollution in generic varargs

An `Object[]` alias lets a `List<Integer>` replace a `List<String>` in a varargs array. The store succeeds, and no exception occurs unless the element is read as a `String`.

Version: Java SE 21

Syntax

static void inspect(List<String>... lists) {
    Object[] alias = lists;
    alias[0] = List.of(42);
}

Generic varargs heap pollution occurs when a reference of a parameterized type ends up pointing to an object that does not match that type. Inside the method, List<String>... lists has type List<String>[]. When you pass lists as individual varargs arguments, Java creates an array whose runtime type is List[]: type erasure means the array does not retain the String type argument.

Array covariance lets Object[] alias = lists refer to the very same array, not a copy. The store alias[0] = List.of(42) puts a List<Integer> into the array without an unchecked warning on that line. The runtime store check looks for a List, not a List<String>, so it does not throw ArrayStoreException. The store itself pollutes the heap: lists[0] still has the static type List<String>.

Calling lists[0].size() does not retrieve an element as a String, so the program finishes without an exception. In contrast, String value = lists[0].get(0); would throw ClassCastException: the compiler-generated cast tries to treat the returned Integer as a String.

Without @SafeVarargs, the declaration and the varargs call shown here produce unchecked warnings. @SafeVarargs is a programmer assertion that suppresses those warnings, not a runtime safeguard. Do not use it on this method. In real code, avoid writing through a wider array alias or exposing the array to code that could do so.

Examples

import java.util.List;

public class HeapPollutionDemo {
    public static void main(String[] args) {
        inspect(List.<String>of());
    }

    static void inspect(List<String>... lists) {
        Object[] alias = lists;
        alias[0] = List.of(42);
        System.out.println("Size: " + lists[0].size());
    }
}

Result

Size: 1

The expected output is `Size: 1`. The empty input list was replaced by a one-element list. The `size()` call does not check that element’s type.

Related lessons

  • Java · Lesson 14 · Advanced · Version: 2

Sources