Is it safe to cast from List to List?

后端 未结 2 1612
夕颜
夕颜 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

    Yes, it's safe. The generic check is just at compile time.

    0 讨论(0)
  • 2021-01-11 18:13

    Type erasure in Java means that all parameterized types are erased at runtime. In your case, a List<Optional> is just a List at runtime and an Optional<MyClass> 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.

    0 讨论(0)
提交回复
热议问题