0

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.

JPG
  • 1,247
  • 5
  • 31
  • 64

3 Answers3

1

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); 
gfelisberto
  • 1,655
  • 11
  • 18
0

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

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0
String obj ="apple";
set1.add(obj);

also see How do I address unchecked cast warnings?

Community
  • 1
  • 1
Georgi
  • 251
  • 4
  • 9