Unchecked assignment warning Unchecked assignment warning java java

Unchecked assignment warning


In your second case when you do:

public void processA(A a)

What do you mean by A? Does it mean A<String> or A<List<String>> or what? You might not be using anything related to type of A, but hey the compiler doesn't know this fact. To compiler, just A is a sign of panic.

In your case, because you dont specifically need to know the type of A, you can:

public void processA(A<?> a) {    Map<Integer, String> map = a.getMap();} 

Having an argument type of A<?> means, you do not specifically care the type of A and just specify a wild card. To you it means: any object of A with any type as its generic type would do. In reality, it means you do not know the type. Its useless because you cannot do anything related to A in typesafe manner as ? can be virtually anything!

But as per your method body, it makes all the sense in the world to use A<?> because no where in the body you actually need the type of A


When you mean to accept an A<T> of any possible type T, but don't need the T, this is correctly expressed by using a wildcard and writing A<?>. Doing so will get rid of the warning in your code:

public void processA(A<?> a) {    Map<Integer, String> map = a.getMap();}

Using the bare type A is not treated equivalently. As explained in the Java Language Specification, raw types like that are not intended to be used in new code:

Unchecked conversion is used to enable a smooth interoperation of legacy code, written before the introduction of generic types, with libraries that have undergone a conversion to use genericity (a process we call generification). In such circumstances (most notably, clients of the Collections Framework in java.util), legacy code uses raw types (e.g. Collection instead of Collection<String>). Expressions of raw types are passed as arguments to library methods that use parameterized versions of those same types as the types of their corresponding formal parameters.

Such calls cannot be shown to be statically safe under the type system using generics. Rejecting such calls would invalidate large bodies of existing code, and prevent them from using newer versions of the libraries. This in turn, would discourage library vendors from taking advantage of genericity. To prevent such an unwelcome turn of events, a raw type may be converted to an arbitrary invocation of the generic type declaration to which the raw type refers. While the conversion is unsound, it is tolerated as a concession to practicality. An unchecked warning is issued in such cases.