Heterogeneous container to store genericly typed objects in Java

In Bloch’s version, Class.cast() is used – which is implemented as return (T) obj, an unchecked cast. It’s cheating in the sense that the compiler warning about unchecked cast is moved to a precompiled lib. The type safety of the cast is not guarded by compiler, but by app logic.

You shouldn’t worry about unchecked cast either. There are type relations that cannot be expressed in the language, but which programmers know to be true. So just overrule the compiler, tell it the cast is safe.

Correction

My understanding about “unchecked cast” was incorrect.

Class.cast() does not contain “unchecked cast”. The cast is done after “checking”, if the cast is reached at runtime, it’s guaranteed to succeed.

T cast(Object obj)
    if obj is instance of this class   // check
        return (T)obj;                 // cast 
    else
        throw new ClassCastException

Leave a Comment