I'm trying to add generics to a Graph class I wrote years ago. Unfortunately, I suppose I didn't grasp the whole concept as well as I thought...
Anyway, the (resumed) Graph interface declaration is:
// The purpose of V and W are explained below
publicinterface Graph<V, W extends Comparable<W>> {
// Some methods
// This represents an edge (note that it is an inner interface)
publicinterface Edge<V, W extends Comparable<W>> {
// Some methods...
}
// This represents a node in the graph (note that it is an inner interface)
publicinterface Node<V> {
// Returns the edges going out or into this node
public <X extends Comparable<X>> Collection<? extends Edge<V, X>> edges();
}
}
V represents the type of each node's label type. For instance, if I want a graph where nodes are cities, I could use the name of the city as the label and so, V would be String.
W represents the weight of an edge (for instance, the distance between two cities). As I will need to compare weights, I decided that W should implement Comparable<W>.
The Node interface is parametrized with V because the Node will include the label. Edge is also parametrized with V because... well, because it connects two Node<V> and with W because it needs the connection's weight.
The method Node::edges() is the source of my problems, because I'm not sure the return type declaration is correct. What I want is to obtain a Collection of Edge<V, W>, where V must be same as the type of the node's label, and W is some Comparable<W>.
When I try to implement these interfaces:
publicclass GraphImpl<V, W extends Comparable<W>> implements Graph<V, W> {
// Graph methods implemented here
publicclass EdgeImpl implements Graph.Edge<V, W> {
// Some methods...
}
publicclass NodeImpl implements Graph.Node<V> {
// This return type results in a warning
public Collection<? extends Edge<V, W>> edges() {
// ... implementation
}
}
}
The NodeImpl::edges() method results in a warning about the return type - "needs unchecked conversion...". Worse than that, when I try to call edges(), I always get the following error:
Bound mismatch: The generic method edges() of type Graph<V,W>.Node<V> is not applicable for the arguments (). The inferred type Comparable<Comparable<X>> is not a valid substitute for the bounded parameter <X extends Comparable<X>>
Why?
Thanks in advance!
Luís Pureza
P.S.: Yes, I know I'm over-complicating... To be honest, all I need is one Graph<String, Double>. Nonetheless, this was sort of an exercise to learn java generics... it's not going so well.