Is it safe to cast from List to List?

后端 未结 2 1646
夕颜
夕颜 2021-01-11 18:02

If you have a raw type in Java, you can safely assign/cast this to the same type with an unbounded wildcard. For example a List can be safely cast to a Li

2条回答
  •  忘掉有多难
    2021-01-11 18:13

    Type erasure in Java means that all parameterized types are erased at runtime. In your case, a List is just a List at runtime and an Optional is just an Optional at runtime.

    When you get a contained class from a List or an Optional, Java makes a cast to the parameterized type. So not only is your code safe, it is exactly what the Java compiler does.

提交回复
热议问题