Java - 不兼容的类型:对象无法转换为类型变量(DFS 中的堆栈)



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

 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<>();

最新更新