Reputation: 1253
I am unable to handle Unchecked cast warning in my java code :
Set<String> set1=new HashSet<String>();
Object obj="apple";
set1=(Set<String>)obj; // warning Type safety: Unchecked cast from Object to Set<String>
in 3rd line I am getting an warning. How can I remove this. Please suggest. I don't want to use suppress warning code.
Upvotes: 0
Views: 296
Reputation: 718758
You can't get rid of the warning without either suppressing it, or completely changing the meaning of the code as written.
And even if you do suppress the warning, you will still get an exception at runtime because you are casting a String
to a Set
. That can never work.
It is difficult suggest a correction because you don't say what you are actually trying to do here. (I can think of three possibilities ...)
Upvotes: 0
Reputation: 251
String obj ="apple";
set1.add(obj);
also see How do I address unchecked cast warnings?
Upvotes: 0
Reputation: 1723
Assuming you are trying to add elements to a Set of Strings your code should be:
Set<String> set1 = new HashSet<String>();
String obj = "apple";
set1.add(obj);
Upvotes: 1