Reputation: 6622
I have an object which is a List my cast is:
List<Object> list = (List<Object>)o;
It seems correct but it gives me:
Type safety: Unchecked cast from Object to ArrayList
still...the casting seems correct to me.
I don't want to use the @suppressWarning, I want to solve it.
Upvotes: 3
Views: 793
Reputation: 22446
The code doesn't compile for a good reason. Consider:
List<Integer> o = new ArrayList<Integer>();
List<Object> list = (List<Object>)o; //Or alternatively (List)o, which does compile, but with a warning
list.add("Hello");
Integer v = o.get(0); //ClassCastException!
The warning/error indicates that the compiler can't guard from unexpected ClassCastException anymore.
Upvotes: 2
Reputation: 728
You cannot get rid of this warning. Casting from an Object
to a generic object always prints this warning (the type system can't guarantee that this step is definitely correct, since Object
might be virtually everything).
Upvotes: 1
Reputation: 9795
You need to give us more code to see if there is a possibility to avoid casting with a proper use of generics.
As for your questions as it is right now, you cannot avoid this compiler warning. It's just because we don't know what is the actual type of o
object. It can be ArrayList
but it can also be BigPapaSmurf
.
Upvotes: 0