Course contentsShow
← Java
Lesson 884 of 2,87021. Generics FundamentalsFree lesson

Type Safety Loss with Raw Types

Why raw types bypass compile-time type checking, allowing any object to be added and requiring manual casts on retrieval.

Type Safety Loss with Raw Types

You'll learn why using raw types removes compile-time type checking, allowing unsafe operations that can fail at runtime.

The Core Problem

When you use a raw type (a generic class without its type parameter), Java essentially turns off the compiler's type-checking safety net. The compiler can no longer verify what types of objects you're storing or retrieving—it trusts you completely, just like Java before generics existed.

This means two dangerous things happen:

  1. You can add ANY object, even the wrong type
  2. You must manually cast when retrieving, and those casts can fail at runtime

How Type Safety Disappears

List rawList = new ArrayList();  // Raw type - no <T>

// Compile-time: No error! Compiler can't check the type
rawList.add("Hello");
rawList.add(42);
rawList.add(new Object());

// All compile successfully, even though this is clearly problematic

// Retrieval requires casting
String str = (String) rawList.get(0);  // Works
Integer num = (Integer) rawList.get(1); // Works
String oops = (String) rawList.get(2);  // RUNTIME ClassCastException!

The compiler doesn't stop you because it has no idea what type should be in the list—you didn't tell it.

The Contrast with Type Safety

List<String> typedList = new ArrayList<>();

typedList.add("Hello");     // OK
typedList.add(42);          // COMPILE ERROR - type safety!

String str = typedList.get(0);  // No cast needed, guaranteed String

Key Takeaway: Raw types bypass compile-time type checking, allowing any object to be added and requiring manual casts that can fail at runtime—eliminating the primary benefit of generics: compile-time type safety.