John said:
No, you're missing the point, which is that the cast can be typechecked
at compile time. More specifically, the cast of an object of generic
type can be typechecked at compile time, making it possible to avoid an
"unchecked cast" warning and *ensure* that no ClassCastException will be
thrown.
I've tested and enhanced your example a little bit, and I may see the
point, but I surely don't agree with it.
package temp;
import java.util.*;
class ListHolder<T>
{
private List<T> list;
public ListHolder(List<T> list)
{
this.list = list;
}
public <S> S getElementAs(Class<S> cls, int i)
{
return cls.cast(list.get(i)); // no warning
// return (S)(list.get(i)); // warning
}
}
class Cast
{
public static void main(String[] args)
{
List<Integer> list = new LinkedList<Integer>();
list.add(new Integer(0));
ListHolder<Integer> holder = new ListHolder<Integer>(list);
// This is compatible
Object o = holder.getElementAs(Object.class, 0);
// This is not
List l = holder.getElementAs(List.class, 0);
}
}
You're right that the Class.cast form does not throw an "unchecked cast"
warning, and the normal cast does. That seems to be the only
difference, however, and you've provided a perfect example of why this
warning is stupid in the first place.