gpt4 book ai didi

Java - 不兼容的类型 : Object cannot be converted to type variable (Stacks in DFS)

转载 作者:行者123 更新时间:2023-12-02 02:57:11 26 4
gpt4 key购买 nike

我正在尝试使用堆栈实现图的深度优先搜索。但是我不断收到有关类型变量的错误。这是我的代码的一部分:

 public Result<T> depthFirstSearchFrom(String vertexId, Predicate< IVertex<T> > pred){
Result<T> result = new Result<T>();
IVertex<T> startVertex = getVertex(vertexId);

Stack stack = new Stack();
stack.add(startVertex);

while (!stack.isEmpty()){
IVertex<T> current = stack.pop();

boolean visited = visitedVertices.contains(tgtVertex);

tgtVertex.getLabel().setParentVertex(current);

if (!visited){
stack.add(tgtVertex);
}
}

if (stack.isEmpty()){
result.setVisitedVertices(visitedVertices);
result.setPathCost(Float.POSITIVE_INFINITY);
}
}
return result;
}

错误发生在以下行:

错误:不兼容的类型:对象无法转换为 IVertex,其中 T 是类型变量

   IVertex<T> current = stack.pop();

错误:未经检查地调用 add(E) 作为原始类型 Vector 的成员,其中 E 是类型变量。

   stack.add(tgtVertex);

最佳答案

只需声明与 startVertex 类型相同的堆栈变量即可。

Stack<IVertex<T>> stack = new Stack<>();

关于Java - 不兼容的类型 : Object cannot be converted to type variable (Stacks in DFS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42889093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com