Why does the try-catch attempt not resolve the warning in unverified generics?

Consider the following MCVEs :

public class MyClass { private LinkedList<Foo> myList = new LinkedList<Foo>(); // Some irrevelant stuff which includes loading myList public void myMethod() { LinkedList<Foo> newList; try { newList = (LinkedList<Foo>) myList.clone(); } catch (ClassCastException e) { // do something in case java screws up } } } 

I know that you can get rid of the warning using @SuppressWarnings("unchecked") , but why does the try/catch not work? Is it a waste of time and energy to put try/catch ?

+4
source share
3 answers

This will not work because you are not getting a ClassCastException for this.

The removed list type cannot be checked at runtime.

You can get a ClassCastException when trying to get something from a list (and it turns out not to be Foo), but the list itself is just a LinkedList (not knowing what its types of elements might be).

The LinkedList<Foo> instance looks like a LinkedList<Bar> at runtime.

The reason for the warning is that the runtime system cannot guarantee that the cast you made is correct (it can check part of the LinkedList, but not the general type).

+7
source

I think that when you explicitly throw something, the compiler does not check for thrown exceptions. The compiler uses a script writer to explicitly type types.

0
source

- Erasure is a process in which Type Parameters and Arguments are removed from a class inside and methods, etc.

- Box<String> becomes Box , it is called Raw Type , where Generic classes and interfaces are removed from their type arguments at compile time

- And this is done so that during Run time it is possible to get compatibility with feedback with those codes that are not used by Generics .

Therefore, the reason for this is not controlled.

0
source

Source: https://habr.com/ru/post/1441538/


All Articles