我需要使用邻接表创建对象图。
我创建了顶点和Edge类,但是我无法管理创建构造函数和基本方法,例如从图形中增加和删除顶点。
我尝试使用HashMap和ArrayList,但是我可以接受更好的主意。
public class Vertex { //for stations
String name; //name of stations
public Vertex(String name) {
this.name = name;
}
public String setName(String n) {
return name = n;
}
public String getName() {
return name;
}
}
public class Edge { //for roads
Vertex start;//source station
Vertex end;//destination station
String name;//name of road
public Edge(Vertex start, Vertex end, String name) {
this.start = start;
this.end = end;
this.name = name;
}
public Vertex setStart(Vertex s) {
return start = s;
}
public Vertex getStart() {
return start;
}
public Vertex setEnd(Vertex e) {
return end = e;
}
public Vertex getEnd() {
return end;
}
public String setName(String n) {
return name = n;
}
public String getName() {
return name;
}
}
import java.util.*;
public class Graph {
List<Vertex> vList;
List<Edge> eList = new ArrayList<>() ;
HashMap<String, ArrayList<Vertex>> adjacencylist;
public Graph() {
vList = new ArrayList<>();
adjacencylist = new HashMap<String, ArrayList<Vertex>>();
}
public Vertex insertVertex(String n) {
Vertex v = new Vertex(n);
vList.add(v);
return v;
}
public Edge insertEdge(Vertex s, Vertex f, String n) {
Edge e = new Edge(s, f, n);
eList.add(e);
return e;
}
}