Given the following code:
interface IParam {}
class Parameter implements IParam {}
void foo(Collection<? extends IParam> params) {
SortedSet<? extends IParam> sortedParams;
if (params instanceof SortedSet)
sortedParams = (SortedSet<? extends IParam>) params;
else
sortedParams = new TreeSet<IParam>(params);
}
What I get is some collection of parameters.
What I need is a SortedSet of the parameters.
If the given collection already is a SortedSet, I want to use that.
Otherwise, I’ll create a new TreeSet with just the content of the given collection.
However, this code doesn’t compile with warnings about unchecked casts.
Is there any way to achieve what I want, without suppressing warnings?
Compiles just fine for me. I would restructure the code slightly though to make it easier to conceptualize and maintain:
As an aside, checking for
instanceofwithin a method, though not illegal, is sometimes a sign of code smell. Your method can be refactored with some overloading: