首页 > 解决方案 > 找不到符号变量... V 扩展类中声明的对象

问题描述

我正在为学校练习 Java,现在遇到了麻烦。

这是我的 Graph.java 文件:

package graph;

public interface Graph<V>{
    public boolean hasEdge(V one, V two);
    public void addNode(V other);
    public void addEdge(V other);
}

这是我的 UndirectedGraph.java 文件:

package graph.undirected;

import graph.*;
import java.util.*;

public class UndirectedGraph<V> implements Graph<V>{

    private HashMap<V,V> neighbourList;
    private TreeMap<V,V> prev;
    private TreeMap<V,Integer> dist;

    public UndirectedGraph(){
        neighbourList = new HashMap<V,V>();
        prev = new TreeMap<V,V>();
        dist = new TreeMap<V,Integer>();
    }

    public boolean hasEdge(V one, V two){
        if(!(this.neighbourList.containsKey(one) && this.neighbourList.containsKey(two))){
            throw new java.util.NoSuchElementException("Nonexistent node.");
        }
        else{
            if( one.neighbourList.containsKey(two) && two.neighbourList.containsKey(one) ){
                return false;
            }
            return true;
        }
    }
    public void addNode(V other){
        if(!(this.neighbourList.containsKey(other))){
            // some code will come here
        }
    }
    public void addEdge(V other){
        if(!(this.neighbourList.containsKey(other))){
            // and some code will come here too
        }
    }
}

我收到以下错误:

graph\undirected\UndirectedGraph.java:23: 错误: 找不到符号 if( one.neighbourList.containsKey(two) && two.neighbourList.containsKey(one) ){ ^ 符号: 变量 neighbourList 位置: V 类型的变量之一,其中 V是一个类型变量:V extends Object 在类 UndirectedGraph graph\undirected\UndirectedGraph.java:23 中声明:错误:找不到符号 if( one.neighbourList.containsKey(two) && two.neighbourList.containsKey(one) ){ ^符号:变量 neighbourList 位置:V 类型的变量二,
其中 V 是类型变量:V 扩展在类 UndirectedGraph 2 中声明的对象

我被困在这里。谁能帮我?

标签: javaclassobjectgenericsextends

解决方案


one并且two是 类型V,在您的示例中出于所有目的都是Object. 这种类型V没有neighbourList字段,所以你不能在下面写,因为它不能编译:

if( one.neighbourList.containsKey(two) && two.neighbourList.containsKey(one) ){

推荐阅读