Course contentsShow
← Java
Lesson 223 of 2,8705. Methods and Function CallsFree lesson

Generic Varargs and Heap Pollution

Understand the @SafeVarargs annotation and the potential heap pollution issues when using varargs with generic types.

Generic Varargs and Heap Pollution

What You'll Learn

You'll understand why mixing varargs with generics can cause subtle runtime errors, and how the @SafeVarargs annotation signals when a method is safe from these issues.

The Problem: Heap Pollution Explained

Heap pollution occurs when a variable of a parameterized type (like List<String>) actually refers to an object of a different parameterized type (like List<Integer>). This breaks Java's type safety guarantees.

When you create a varargs method with a generic type parameter, Java must create an array to hold those arguments. But generic arrays have a dangerous quirk: the compiler can't enforce type safety at runtime because of type erasure.

Think of it like a package delivery system. You label a box "Fragile Glass" (generic type), but the conveyor belt system (varargs array) can only see "Box" and might accidentally mix your glassware with someone else's metal tools. When you open the box expecting glass, you might get a nasty surprise.

The @SafeVarargs Annotation

@SafeVarargs is your promise to the compiler: "I've checked this method, and it won't cause heap pollution problems." Use it when:

  • Your method doesn't store anything in the varargs array
  • Your method doesn't leak the array reference to untrusted code

This suppresses the compiler warnings about potential heap pollution.

@SafeVarargs
static <T> void safePrint(T... items) {
    for (T item : items) {
        System.out.println(item);  // Only reading—safe
    }
}

Without @SafeVarargs, the compiler would warn you about potential unsafe operations.

Key Takeaway: Use @SafeVarargs on methods that accept generic varargs when you're certain they only read from the array and don't expose it externally, preventing heap pollution runtime errors.