Back to the original question ...
As far as I got it will any cast to a generic type trigger the unchecked warning as the compiler cannot check if it is correct (so it remains unchecked ...).
So there is no other way to get rid of the warning than to use to @SuppressWarnings annotation.
But applying it to the method at a whole is usually not a good idea if the method is a bit longer than just a few lines - although this is the way Eclipse is doing it for you ...
Instead the annotation should be assigned to the location where the cast is performed.
Assume the following code sequence:
public List<String> method()
{
return (List<String>
getList();
}
The return statement will cause the warning that can be suppressed by
@SuppressWarnings( "unchecked" )
public List<String> method()
{
return (List<String>
getList();
}
But when later code will be added to the method (perhaps additional casts ...), no warning will be thrown. So my recommendation is to write it as follows:
public List<String> method()
{
@SuppressWarnings( "unchecked" )
List<String> retValue = (List<String>
getList();
return retValue;
}
Now only the warning caused by the assignment to retValue is suppressed - for the price of an additional local variable. Unfortunately the annotation can only be assigned to declarations, so the code below does not work:
public List<String> method()
{
List<String> retValue = null;
@SuppressWarnings( "unchecked" )
retValue = (List<String>
getList();//Does not work!!!
return retValue;
}
In this case another helper variable might be necessary.
When the coder assigns the @SuppressWarnings annotation somewhere she makes a statement: it documents that he knows that the code sequence is somehow problematic, AND that he has taken appropriate precautions against any error conditions (if necessary at all). This Collection.emptyList() method is exactly that: as the list is empty it is ensured that is compatible to any type of List (as the generic "type" of a list is in fact the type of the List's contained elements).