How to fix unchecked call warning in Java?

Java

Java Problem Overview


Here is the code I have written?

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

The warning I'm getting is:

warning: [unchecked] unchecked call to TreeSet(java.util.Collection<? extends E>) as a
         member of the raw type java.util.TreeSet

How do I get rid of the compiler warning?

Java Solutions


Solution 1 - 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);

Solution 2 - Java

As far as this problem is concerned, you should use parameterized type of keys e.g

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

where TypeOfKeyObject is object type of Key in your map object.

you may force supress the warnings (as already correctly suggested) but not advisable.

At the risk of sounding condescending, I would suggest you to study generics. A good starting point would be this: http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser658338View Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaNishantView Answer on Stackoverflow