内部静态泛型类&lt; <不能=“”已解决=“”to =“”a =“”type =“”>&gt; </不能>

时间:2015-01-06 03:23:24

标签: java graph

我正在尝试使用 HashMap 泛型创建相邻的图表列表。
但是,我不明白为什么我会收到错误“ Edge无法解析为

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException{
        Scanner sc=new Scanner(new File("input.txt"));
        PrintWriter pw=new PrintWriter(new File("output.txt"));
        int roads = sc.nextInt(); // How many Edges we have
        int vertices = sc.nextInt(); // How many vertices Graph has
        Graph<String> g = new Graph<String>(vertices); // Every Vertex is a String
        for (int i=0;i<roads;i++) {
            g.add(sc.next(), sc.next());
        }
        //Here i get an error
        Edge<String> e; //Edge cannot be resolved to a type
    }
    static class Graph<E> {
        HashMap<E,Edge<E>> m;

        public Graph(int vertices) {
            m = new HashMap<E,Edge<E>>(vertices);
        }

        public void add(E from,E to) {
            if (m.get(from)==null) m.put(from,new Edge<E>(to,null));
            else m.put(from, new Edge<E>(to,m.get(from)));
        }
        //Storing Graph as an adjacent list of edges
        static class Edge<E> {
            E to;
            Edge<E> prev;
            public Edge(E to, Edge<E> prev) {
                this.to = to;
                this.prev = prev;
            }
        }
        //
    }
}

请详细解释......
提前致谢

2 个答案:

答案 0 :(得分:1)

请勿尝试在Edge中包含Graph。将其移动到并行类或外部类。像

这样的东西
public class Main {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(new File("input.txt"));
        PrintWriter pw = new PrintWriter(new File("output.txt"));
        int roads = sc.nextInt(); // How many Edges we have
        int vertices = sc.nextInt(); // How many vertices Graph has
        Graph<String> g = new Graph<String>(vertices); // Every Vertex is a
                                                        // String
        for (int i = 0; i < roads; i++) {
            g.add(sc.next(), sc.next());
        }
        // Here i get an error
        Edge<String> e; // Edge cannot be resolved to a type
    }

    static class Graph<E> {
        HashMap<E, Edge<E>> m;

        public Graph(int vertices) {
            m = new HashMap<E, Edge<E>>(vertices);
        }

        public void add(E from, E to) {
            if (m.get(from) == null)
                m.put(from, new Edge<E>(to, null));
            else
                m.put(from, new Edge<E>(to, m.get(from)));
        }
    }

    // Storing Graph as an adjacent list of edges
    static class Edge<E> {
        E to;
        Edge<E> prev;

        public Edge(E to, Edge<E> prev) {
            this.to = to;
            this.prev = prev;
        }
    }
}

答案 1 :(得分:0)

EdgeGraph中的内部类,因此在Graph内你可以称之为Edge ......但main不是{\ n}在Graph内。

从类Main内部(包括方法main),您可以将其称为Graph.Edge(通用参数为Graph.Edge<String>)。< / p>

在课程Main之外,您可以将其称为Main.Graph.Edge(使用泛型,Main.Graph.Edge<String>)。