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?
An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
The warning tells you that the compiler has encountered a condition that it can't guarantee the sense of. You should avoid having this kind of thing.
If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With