2

I want to be sure if the object I get is a List of Strings. Here's my code:

Object obj = plugin.getConfig().get("groups");
if(obj instanceof List<?>){ // Is the Object a List ?
    List<?> list = (List<?>) obj;
    if(list.get(0) instanceof String){ // Does the List contain Strings ?
        List<String> groupList = (List<String>) list;
    }
}

But Eclipse says that the last cast on line 5 isn't safe:

Type safety: Unchecked cast from List<capture#3-of ?> to List<String>

How can I fix that? I've also tried

List<String> groupList = (List<String>) obj;

...but I still get the same error (basically).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Franckyi
  • 243
  • 3
  • 12

1 Answers1

-1

Bottom line is, you cannot prevent this warning if you want to do a cast of the whole list, you can only supress it with an annotation.

See this answer for an explanation (it's about Map instead of List, but the same principles apply): How do I address unchecked cast warnings?

If you want to have code without unsafe casts and without annotations you can take the approach in the accepted answer from the above question: do not cast the list itself, but iterate through the List<?> and cast each individual Object to String.

Community
  • 1
  • 1
sebkur
  • 658
  • 2
  • 9
  • 18