I have an application that performs various analysis algorithms on graphs of nodes and edges G(N,E). The attributes of the nodes and edges vary with the application and form an inheritance hierarchy based on the type of graph and nature of the attributes. For example the root of the Node hierarchy could represent the most general Non-directed Cyclic Graphs (NcgNode). A sub-class of NcgNode might represent directed cyclic graphs (DcgNode), followed by DagNode, etc. The algorithms that can be applied to DAGs are different from those of NCGs, but not visa-versa. A key behavior of the root of the tree is to add and retrieve adjacent nodes of the graph. The question is how to do this without creating an "unchecked" exception?
A terse version of the code might look like this:
import java.util.ArrayList;
import java.util.List;
public class NcgNode {
private List<NcgNode> nodeList_ = null;
private List<? extends NcgNode> nodeListSrc_ = null;
private List<? super NcgNode> nodeListSink_ = null;
public <N extends NcgNode> void addNode(N node) {
if (nodeList_ == null) {
nodeList_ = new ArrayList<NcgNode>();
nodeListSrc_ = nodeList_;
nodeListSink_ = nodeList_;
}
nodeListSink_.add(node);
}
@SuppressWarnings("unchecked")
// Any way to avoid this?
public <N extends NcgNode> N getNode(int n) {
if ((nodeList_ == null) || (n >= nodeList_.size()))
return null;
// causes unchecked warning:
return (N) nodeListSrc_.get(n);
}
}
class DcgNode extends NcgNode {
// enables DCG algorithms, etc
}
class DagNode extends DcgNode {
// enables DAG algorithms, etc.
}
Is there a better way to design this?