ArrayList Generic without Type

后端 未结 5 1043
执念已碎
执念已碎 2020-12-03 08:32

recently I read a piece of code which seems weird to me. As we know, we need to initialize the generic type in collections when we need to use them. Also, we know Collection

5条回答
  •  日久生厌
    2020-12-03 08:56

    Java generic collections are not stored with a type to ensure backwards compatibility with pre J2SE 5.0. Type information is removed when added to a generic collection. This is called Type Erasure.

    This means that a generic collection can be assigned to a non generic reference and objects in a generic typed collection can be placed in an non generic, nontyped collection.

    All Java generics really does is make sure you can't add the wrong type to a generic list and saves you from doing an explicit cast on retrieval; even though it is still done implicitly.

    Further to this

    • the Java section of this answer goes a little deeper into what I just said
    • this article also covers basically what you were asking in a more complete way
    • other things to watch out for with Type Erasure

提交回复
热议问题