问题
I am implementing a graph class using a Map as an adjacency list, with a simple class Vertex that I am using to represent each node in the graph:
export class Vertex {
constructor(value) {
if (value) this.value = value;
else throw new Error("Value must be specified");
}
getValue() {
return this.value;
}
setValue(value) {
if (value) this.value = value;
else throw new Error("Value must be specified");
}
}
Then in my graph class I have implemented a constructor and 2 methods for adding vertices and edges:
export class UndirectedGraph {
constructor() {
this.adjacencyList = new Map();
}
addVertex(value) {
if (value) {
const vertex = new Vertex(value);
this.adjacencyList.set(vertex, []);
}
}
addEdge(to, from) {
if (
!to ||
!from ||
!(to.constructor === Vertex && from.constructor === Vertex)
) {
throw new Error("Arguments must be of type Vertex");
}
if (
!this.adjacencyList.get(to) ||
!this.adjacencyList.get(from)
) {
throw new Error(
"Both arguments must already be nodes in this undirected graph"
);
}
this.adjacencyList.get(to).push(from);
this.adjacencyList.get(from).push(to);
}
getAdjacencyList() {
return this.adjacencyList;
}
}
Then I want to call the addEdge()
function to create an edge between 2 instances of type Vertex:
const graph = new UndirectedGraph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("B");
graph.addEdge(..., ...);
What do I pass to the addEdge()
function to create an edge between "A" and a particular instance of "B"? I have no variable for the Vertex instances that I can reference.
I want the graph to be able to store duplicate values, such as names, so using class instances seems like the obvious choice but now I am stuck on how to access the values they contain because I am unsure how to search for class instances within the Map i.e. graph.getAdjacencyList().get(...)
. All help appreciated
回答1:
Given your addVertex
method creates the Vertex
instance and the addEdge
method expects that very instance as a parameter, you need to make it available to the caller of these methods - by return
ing it:
…
addVertex(value) {
if (value) {
const vertex = new Vertex(value);
this.adjacencyList.set(vertex, []);
return vertex;
}
// else throw new Error("no value given")?
}
…
Then you can use it like
const graph = new UndirectedGraph();
const vertex1 = graph.addVertex("A");
const vertex2 = graph.addVertex("B");
const vertex3 = graph.addVertex("B");
graph.addEdge(vertex1, vertex2);
graph.addEdge(vertex1, vertex3);
graph.addEdge(vertex2, vertex3);
来源:https://stackoverflow.com/questions/59309381/how-can-i-reference-class-instances-that-i-have-passed-into-a-map-as-keys-javasc