List vs List<Object>

前端 未结 6 863
借酒劲吻你
借酒劲吻你 2020-12-10 03:56

Why do we lose type safety when using List and not while using List? Aren\'t they basically the same thing?

EDIT

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 04:44

    Type Erasure is one answer and the backward compatibility to pre Java 1.5 and tighter type check in case of first one.

    Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:

    Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods. Insert type casts if necessary to preserve type safety. Generate bridge methods to preserve polymorphism in extended generic types. Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

提交回复
热议问题