Java: Casting Object to a generic type

后端 未结 3 500
清酒与你
清酒与你 2021-02-05 09:27

In Java when casting from an Object to other types, why does the second line produce a warning related to the cast, but the first one doesn\'t?

void a(Object o)          


        
3条回答
  •  北海茫月
    2021-02-05 10:18

    For clarity, let me slightly rewrite the examples...

    I would say, the cruxial difference between:

    void a(Object o) {
      Integer i = (Integer) o;
      ...
    }
    

    and

    void a(Object o) {
      List list = (List) o;
      ...
    }
    

    is that, given that there is a type-error, the first cast will always immediately throw a RuntimeException (specifically, a ClassCastException) when executed.

    While the second one might not -- as long as the input parameter o is any kind of List, execution will just proceed, in spite of an incorrect cast.

    Whether the code will somewhere later throw an exception or not, depends upon what you do with the list.

    But regardless, an Exception might not be thrown at the line where the cast was made, but somewhere else (which might be a difficult bug to trace down) or not at all.

    That's what I understand, is the reason the compiler-designers considered a warning appropriate in the second case only.

提交回复
热议问题