我正在尝试使用 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;
}
}
//
}
}
请详细解释......
提前致谢
答案 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)
Edge
是Graph
中的内部类,因此在Graph
内你可以称之为Edge
......但main
不是{\ n}在Graph
内。
从类Main
内部(包括方法main
),您可以将其称为Graph.Edge
(通用参数为Graph.Edge<String>
)。< / p>
在课程Main
之外,您可以将其称为Main.Graph.Edge
(使用泛型,Main.Graph.Edge<String>
)。