Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Generics — Wildcards, Bounded Types, PECS

Why does Java warn about generic varargs (heap pollution), and what does @SafeVarargs actually assert?

Level IV · SeniorGenerics — Wildcards, Bounded Types, PECS
Answer

A varargs parameter is implemented as an array, but you can't have an array of a parameterized type, so the compiler creates an array of the erased type and you can get heap pollution — a reference of one parameterized type pointing at data of another, surfacing as a ClassCastException later. @SafeVarargs is the author's promise that the method only reads from the varargs array and never stores into it or exposes it, so the warning is safe to suppress. Misapplying it to a method that does store into the array reintroduces the unsafety.

Common mistakes
  • Adding @SafeVarargs without checking the method never stores into the varargs array.
  • Ignoring unchecked warnings instead of understanding them.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Generics — Wildcards, Bounded Types, PECS.

Practise free

More on Generics — Wildcards, Bounded Types, PECS