[英]Passing a specific class argument to a Java Generic Function
所以,我是 Java 泛型的新手。 我正在使用 hashMap 和 hashSet 构建图形和邻接列表。 我已经使用泛型编写了类及其方法。 我还将 T 扩展到 Node。 打印邻接表,
public class Graph<T extends Node>{
public static int time;
private HashMap<T, HashSet<T>> adjacencyList;
public Graph(){
this.adjacencyList = new HashMap<>();
}
void printAdjacencyList(HashMap<T,HashSet<T>> adj){
for(T n : adj.keySet()){
System.out.print("Key: " + n.getValue()+"\t");
Iterator<T> i = adj.get(n).iterator();
while(i.hasNext()){
System.out.print(" "+i.next().getValue());
}
System.out.println();
}
}
}
public static void main(String[] args){
Graph<Node> G = new Graph<>();
// have added vertices and edges
printAdjacencyList(G.adjacencyList);
}
此处, G.adjacencyList的类型为HashMap<Node,HashSet< Node >> 。 Node 是另一个有几个成员的类。
但是,我遇到了编译错误: Graph 类型中的方法 printAdjacencyList(HashMap<T,HashSet < T >>) 不适用于参数 (HashMap<Node,HashSet < Node >>)
因此,据我所知,它是说我明确地编写了一个以HashMap<Node, HashSet < Node > >作为参数的函数。 有什么方法可以以某种方式使用泛型函数(而不是编写带有必需参数的新函数)。
问题是你想传递一个HashMap<Node, Set>
但它想要一个HastMap<Node, HastSet>
。
每个HashSet
也满足Set
的要求,但反之则不然。
解决方案1:
void printAdjacencyList(HashMap<T,HashSet<T>> adj){
=>
void printAdjacencyList(HashMap<T,Set<T>> adj){
解决方案2:
private HashMap<T, Set<T>> adjacencyList;
=> private HashMap<T, HashSet<T>> adjacencyList;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.