I am reading about Java Generics and I came across this topic where I am a bit confused.
From : http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ205
public abstract class Node <N extends Node<N>> { private final List<N> children = new ArrayList<N>(); private final N parent; protected Node(N parent) { this.parent = parent; parent.children.add(this); // error: incompatible types } public N getParent() { return parent; } public List<N> getChildren() { return children; } } public class SpecialNode extends Node<SpecialNode> { public SpecialNode(SpecialNode parent) { super(parent); } } Scrolling lower a couple of screens...
public abstract class Node <N extends Node<N>> { ... protected Node(N parent) { this.parent = parent; parent.children.add( (N)this ); // warning: unchecked cast } ... } Casts whose target type is a type parameter cannot be verified at runtime and lead to an unchecked warning. This unsafe cast introduces the potential for unexpected ClassCastException s and is best avoided.
Could someone give me an example where the above code throws a ClassCastException ?
Thanks.