Why do the following codes not trigger an “unchecked throw” warning?

I think that (String)xthis is an uncontrolled selection, but the compiler does not give any warnings. Why is this happening?

public static void main(String[] args) {
        Object x=new Object();
        String y=(String)x;
    }
+4
source share
2 answers

I think this (String)xis an unchecked listing.

No no. It is checked at runtime - if the cast is invalid, it throws an exception.

Unchecked throws are throws that look as if they will check, but do not actually check everything that you expect, due to type erasure. For instance:

List<String> strings = new ArrayList<>();
Object mystery = strings;
List<Integer> integers = (List<Integer>) mystery;
integers.add(0); // Works
String x = strings.get(0); // Bang! Implicit cast fails

(List<Integer>) mystery , mystery, - List - not a List<Integer>. Integer , , List<Integer>.

, , "" - add , Object[] Integer. , get() .

, :

List strings = new ArrayList();
Object mystery = strings;
List integers = (List) mystery;
integers.add(0);
String x = (String) strings.get(0);
+4

Java

+1

All Articles