Java - 类型不匹配(但两者都来自同一类型?!):无法从 HashMap<Integer,ArrayList<Integer>> 转换为 HashMap<Intege



编辑:问题已解决:请参阅Karim SNOUSSI的答案和我下面的评论。


这是我在 Stack Overflow 上的第一个问题,所以我可能不会在一开始就把所有事情都做好。对不起。此外,我对Java和一般编程都是新手。

我遇到了一个奇怪的错误,无法真正理解解决方案可能是什么。

当尝试将hashMap从一个类传递到另一个类时,IDE日食说:类型不匹配:无法从 HashMap> 转换为 HashMap>

但是如果我做对了,两者都是同一类型,所以不知道有什么问题。

这是我的代码:我只发布其中的一部分,所以不会把所有的东西都弄乱

我的类中有一个名为graph.class的HashMap, 它用于方法 public HashMap>getAllShortestPaths(( 其中将计算从每个节点到图形中任何其他节点的所有最短路径 并存储到哈希图中以供进一步处理。 这工作正常,当将地图打印到屏幕上时,如果我想从其中的方法进行操作,它会正确显示所有信息。

但我的目的是将此hashMap传递给另一个类,在那里我将收集我对图形的整个分析并将其保存到一个新文件中。

public class Graph {
.
.
private HashMap<Integer, ArrayList<Integer>> shortestPathsMap = new HashMap<Integer, ArrayList<Integer>>();

. . .

public HashMap<Integer, ArrayList<Integer>> getShortestPathsMap() { return shortestPathsMap; }
.
.
.
public void getAllShortestPaths() {
for(int i = 0; i < getNodeCount(); i++) {
ArrayList<Integer> shortestPathMapValues = new ArrayList<>();   // saves ... 
for(int n = i; n < getNodeCount(); n++) {
shortestPathMapValues.add(n);                               // the corresponding node id's and ..
shortestPathMapValues.add((int) shortestPath(i,n));         // the outcome of shortestPath() calculation
}
shortestPathsMap.put(i, shortestPathMapValues);                 // saves the first node id and the corresponding values
}
}
.
. 

因此,为了进行测试,我将其传递给了主服务器.class并且确实想将其打印到屏幕上:

public HashMap<Integer, ArrayList<Integer>> getShortestPathsMap() { 
return shortestPathsMap; 
}
public class Main {
public static void main(String[] args) {
.
.
.
G.getAllShortestPaths();
HashMap<Integer, ArrayList<Integer>> spMap = new HashMap<Integer, ArrayList<Integer>>();
spMap = G.getShortestPathsMap();
// iterate and display values
for(Entry<Integer, ArrayList<Integer>> entry : spMap.entrySet()) {
int key = entry.getKey();
ArrayList<Integer> values = entry.getValue();
System.out.println("Key = " + key);
System.out.println("Values = " + values);
}
.
.
. 

在主.class,在以下行:spMap = G.getShortestPathsMap((;IDE 将显示

类型不匹配:无法从 HashMap>转换为 HashMap>

但:

HashMap<Integer, ArrayList<Integer>> spMap = new HashMap<Integer,Integer, ArrayList<Integer>>();
HashMap<Integer, ArrayList<Integer>> shortestPathsMap = new HashMap<Integer, ArrayList<Integer>>();

spMap 和 shortestPathsMap 属于同一个典型值,不是吗?

我很高兴收到任何有用的回复,并提前感谢您。

尝试在主方法中替换它

HashMap<Integer, ArrayList<Integer>> spMap = new HashMap<Integer, ArrayList<Integer>>();
spMap = G.getShortestPathsMap();

有了这个

Map<Integer, ArrayList<Integer>> spMap = G.getShortestPathsMap();

相关内容

最新更新