Phate
Phate

Reputation: 6622

Warning when I try to cast Object to List<Object>

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

Answers (3)

Eyal Schneider
Eyal Schneider

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

Andreas Wiese
Andreas Wiese

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

darijan
darijan

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

Related Questions