Generics & Inheritance Question
I have an inheritance structure that forms a tree of classes of Nodes.
One shared property of these classes is to be able to manage a list of classes
of type Node or a sub-type of Node.
Can this be done without creating an "unchecked" exception?
Code:
public class Node {
private List<Node> list_ = null;
private List<? extends Node> listSrc_ = null;
private List<? super Node> listSink_ = null;
public <N extends Node> void add(N node) {
if (list_ == null) {
list_ = new ArrayList<Node>();
listSrc_ = list_;
listSink_ = list_;
}
listSink_.add(node);
}
@SuppressWarnings("unchecked") //Any way to avoid this?
public <N extends Node> N get(int n) {
if ((list_ == null) || (n >= list_.size())) return null;
return (N)listSrc_.get(n); //causes unchecked warning:
}
}
class Bnode extends Node { // ...}
class Cnode extends Bnode { // ... }
//etc.