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:
publicclass 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()))
returnnull;
//causes unchecked warning:
return (N)nodeListSrc_.get(n);
}
}
class DcgNode extends NcgNode {
//enables DCG algorithms, etc
}
class DagNode extends DcgNode {
//enables DAG algorithms, etc.
}
In short: It's just a warning that you can acknowledge and supress.
(In long:) I don't think that there's a simple way to get rid of it. The get method just returns an Object. Checking the cast is done at runtime and, due (I think) to the way that Java does type erasure, the type of the Object cannot be guaranteed at compile time - hence the warning.
This problem, and some possible solutions, are discussed below but it seems to be generally agreed that the solutions are more complex than the problem (and a lot more complex than adding a "supress warnings" label).
> The > question is how to do this without creating an "unchecked" > exception?
Not sure about Net Beans and IntelliJ (IDEA) but in Eclipse you can configure it to Ignore Unchecked Generics - in your preferences. If the Warning is being spat out during your Ant/Maven Build, I'm sure there should be ways or flags to ignore this too.