Monday, September 04, 2006

expression of type X needs unchecked conversion

Ok, so you are using generics in Java but you also work with "legacy" code that has been written without generics. For example, you want to assign a return type ArrayList to a variable of type ArrayList .

Then you might experience a compiler warning similar to the following one:
Type safety: The expression of type List needs unchecked conversion to conform to List
As the compiler tries to statically check the type safety there is no way it can find out whether the raw type list actually contains only instances of YourType.

The solution is to add the following annotation in front of the method for which the warning is reported:
@SuppressWarnings("unchecked")
Note that the generic ArrayList<> is always compiled into the raw type ArrayList. The same applies for all other collections in java.util. The reason is that this type information is removed in order to stay backward compatible. Therefore in Java 5 all instances of ArrayList are mapped to the raw type ArrayList.

For C++ and also for .NET 2.0 and later the designers chose a different solution. In C++ each instance of the template ArrayList is compiled into separate object code. This can lead to code bloat. In .NET 2.0 and later the type information is retained and is available during runtime.