What is a raw type in Java, and why does the compiler still permit using them (with an unchecked warning) despite generics having been available since Java 5?
Short answer
A raw type is a generic class used WITHOUT any type argument at all (List instead of List or List ), retained purely for backward compatibility with pre-Java-5 code and bytecode that predates generics entirely, since generic classes are compiled to the same underlying bytecode…
Advertisement
AModel answer
A raw type is a generic class used WITHOUT any type argument at all (List instead of List<String> or List<?>), retained purely for backward compatibility with pre-Java-5 code and bytecode that predates generics entirely, since generic classes are compiled to the same underlying bytecode as their raw-type equivalent (due to type erasure) -- using a raw type in new code sacrifices all of generics' compile-time type safety (producing 'unchecked' warnings for any operation the compiler can no longer verify), and modern code should essentially always use either a properly parameterized type or an unbounded wildcard (List<?>) instead, reserving raw types exclusively for genuinely necessary interop with old, unmigrated legacy code.
List rawList = new ArrayList(); // raw type -- compiles, but loses ALL generic type safety
rawList.add("hello");
rawList.add(42); // no compile-time error at all, unlike a properly parameterized List<String>
// Generates an "unchecked" compiler warning
@SuppressWarnings("unchecked")
List<String> unsafeCast = rawList; // legal but genuinely unsafe if rawList actually contains mixed typesReal-world example
A codebase interfacing with a very old, unmaintained third-party library predating generics is forced to use raw types at that specific integration boundary, carefully isolating and immediately converting to properly parameterized types as soon as possible afterward, to contain the loss of type safety to the smallest necessary surface area.
Likely follow-ups
- What specific unchecked warnings does the compiler generate when working with raw types, and why should they never be silently ignored?
- How does mixing raw types and generic types in the same codebase create particularly confusing type-safety holes?
Related topics