Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of the type safety warning in certain Java generics casts?

What is the meaning of the Java warning?

Type safety: The cast from Object to List<Integer> is actually checking against the erased type List

I get this warning when I try to cast an Object to a type with generic information, such as in the following code:

Object object = getMyList(); List<Integer> list = (List<Integer>) object; 
like image 702
Mike Stone Avatar asked Aug 02 '08 08:08

Mike Stone


People also ask

What is type safety in Java generics?

1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other objects. Without Generics, we can store any type of objects. List list = new ArrayList();

How generics improve type safety explain with generic class code?

Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

Does generics provide type safety?

By using generics , developers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

Why are generics type safe?

Generics are type safe because generics are available at run time, It means the runtime knows what type of data structure you're using and can store it in memory more efficiently.


1 Answers

This warning is there because Java is not actually storing type information at run-time in an object that uses generics. Thus, if object is actually a List<String>, there will be no ClassCastException at run-time except until an item is accessed from the list that doesn't match the generic type defined in the variable.

This can cause further complications if items are added to the list, with this incorrect generic type information. Any code still holding a reference to the list but with the correct generic type information will now have an inconsistent list.

To remove the warning, try:

List<?> list = (List<?>) object; 

However, note that you will not be able to use certain methods such as add because the compiler doesn't know if you are trying to add an object of incorrect type. The above will work in a lot of situations, but if you have to use add, or some similarly restricted method, you will just have to suffer the yellow underline in Eclipse (or a SuppressWarning annotation).

like image 101
Mike Stone Avatar answered Oct 11 '22 11:10

Mike Stone