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;
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();
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With