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.
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);
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 ...)
String obj ="apple";
set1.add(obj);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.