I’m making a method that load a graph from a file. It’s very simple, but if there are repeated vertex, the method’ll insert too into the graph, so I’m trying to avoid this.
This is my current code:
public static Graph<ElementoDecorado<Integer>, String> loadGraphFromFile(File f) {
boolean v1_exists = false, v2_exists = false;
Graph<ElementoDecorado<Integer>, String> g = new AdjacencyListGraph<ElementoDecorado<Integer>, String>();
Vertex<ElementoDecorado<Integer>> v1, v2, aux = null;
Scanner fr;
try {
fr = new Scanner(f);
while(fr.hasNextLine()) {
v1 = g.insertVertex(new ElementoDecorado<Integer>(fr.nextInt()));
v2 = g.insertVertex(new ElementoDecorado<Integer>(fr.nextInt()));
for(Vertex<ElementoDecorado<Integer>> v : g.vertices()) {
if(v.equals(v1)) {
/*aux = v;
v1_exists = true;*/
}
if(v.equals(v2)) {
/*aux = v;
v2_exists = true;*/
}
}
g.insertEdge(v1, v2, "edge");
v1_exists = v2_exists = false;
}
} catch(FileNotFoundException e) {
e.printStackTrace();
}
return g;
}
I don’t know what to write into the two ifs. I have tried to delete the vertex if they are equal but obviously this doesn’t work cause at the end my graph’ll be empty :S
This is the manual page for the Vertex interface.
Any help is welcome.
Thanks, and merry christmas!
You should first check what
graph.insertVertex(V value)does. If the package was build decently (which I doubt from the poor documentation), then that method will only create a new vertex if a vertex withvaluedoes not already exist; otherwise it returns the existing vertex of valuevalue.However I can’t tell from the non-documentation whether the package really assumes that there is a single vertex for a given value and whether
insertVertexbehaves correctly.Here is some code in case
insertVertexdoes not check for duplication:(I replaced
ElementoDecorado<Integer>byIntegerfor readability)