I tried to write the following:
public class AdjacencyList<Vertex> {
Map<Vertex, Set<Edge<Vertex>>> adj = new HashMap<Vertex, HashSet<Edge<Vertex>>>();
}
But I get the error:
Type mismatch: cannot convert from HashMap<Vertex,HashSet<Edge<Vertex>>> to Map<Vertex,Set<Edge<Vertex>>>
Eclipse wants me to change the line to:
Map<Vertex, HashSet<Edge<Vertex>>> adj = new HashMap<Vertex, HashSet<Edge<Vertex>>>();
(Note it's specifying the type of Set
on the left.
I'm trying to get into the habit of specifying interfaces instead of exact types. Why is it not letting me in this case?
covariance
andcontravariance
. In short words,List<String>
is not an instance/subclass ofList<Object>
because if it were then issues arise from using the generic type instance as parameters or return types.