How to fix unchecked call warning in Java?

Ideally, start using generics fully. You haven’t shown what the type of map is, but ideally you should be able to write something like:

Set<String> keys = map.keySet();
SortedSet<String> s = new TreeSet<String>(keys);

That would be in the case where map was something like a Map<String, Integer>.

If map itself is a raw type, it’s harder – again, the best fix would be to start adding generics throughout your code base, getting rid of raw types. That’s not always possible if the map is returned from third party code, of course. In that case, you may need to suppress warnings on one line as you convert from raw types to generic types – possibly via Collections.checkedCollection – but after that, you should be able to work with the generic type “properly”. For example:

@SuppressWarnings("unchecked") // Just for this one statement
Collection<String> keys = Collections.checkedCollection(map.keySet(),
                                                        String.class);

// Now this statement is fully generic with no warnings
SortedSet<String> s = new TreeSet<String>(keys);

Leave a Comment