3

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.

Phate
  • 6,066
  • 15
  • 73
  • 138

3 Answers3

2

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.

Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
  • The compiler can't guard against ClassCastException when casting from Animal to Dog either. So what? – Hot Licks Mar 26 '14 at 11:58
  • @HotLicks: I was talking about **unexpected** ClassCastException. Not one that occurs on an explicit cast. Remember that Java generics adds implicit cast instructions, and they may fail if the code is not type safe. – Eyal Schneider Mar 26 '14 at 11:58
  • So this is the only "unexpected" failure that can occur in a Java program?? – Hot Licks Mar 26 '14 at 12:04
  • @HotLicks: I wasn't saying that. I was talking about the presence of the type safety warning (which is not the case here), and its possible implication - a ClassCastException on an implicit cast. – Eyal Schneider Mar 26 '14 at 12:06
  • I'm saying you can spend too much time worrying about casts and warnings for generics and not enough worrying about the 10 thousand other ways you can eff something up. If you know what you're casting then do it. Put a comment on the line to acknowledge what you're doing, then get on with life. – Hot Licks Mar 26 '14 at 21:10
1

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).

Andreas Wiese
  • 718
  • 3
  • 8
0

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.

darijan
  • 9,725
  • 25
  • 38