From b4c5575bec58206c0c85490c212634e6d7f583cf Mon Sep 17 00:00:00 2001 From: Giacomo Date: Thu, 13 Jun 2019 18:07:17 +0200 Subject: [PATCH] Save/Load * added class for save/load --- src/berack96/sim/util/graph/Graph.java | 29 ++++++++++++++------------ 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/berack96/sim/util/graph/Graph.java b/src/berack96/sim/util/graph/Graph.java index bc0a228..63a141f 100644 --- a/src/berack96/sim/util/graph/Graph.java +++ b/src/berack96/sim/util/graph/Graph.java @@ -4,7 +4,6 @@ import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Collection; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; @@ -548,13 +547,11 @@ public interface Graph extends Iterable { Map>> distance(V source) throws NullPointerException, IllegalArgumentException; static void save(Graph graph, String file) throws IOException { - Map map = new HashMap<>(); - map.put("vertices", graph.vertices()); - map.put("edges", graph.edges()); - + GraphSaveStructure save = new GraphSaveStructure<>(graph); Gson gson = new Gson(); FileWriter writer = new FileWriter(file); - writer.write(gson.toJson(map)); + + writer.write(gson.toJson(save)); writer.close(); } @@ -570,15 +567,21 @@ public interface Graph extends Iterable { while((c = reader.read()) != -1) fileContent.append((char)c); reader.close(); - Map map = gson.fromJson(fileContent.toString(), Map.class); + GraphSaveStructure save = gson.fromJson(fileContent.toString(), GraphSaveStructure.class); - Collection vertices = (Collection)map.get("vertices"); - graph.addAllVertices(vertices); - - Collection>collection = (Collection>)map.get("edges"); - for (Map edge : collection) { - graph.addEdge((V) edge.get("source"), (V) edge.get("destination"), (W) edge.get("weight")); + graph.addAllVertices(save.vertices); + graph.addAllEdges(save.edges); + } + + class GraphSaveStructure { + public GraphSaveStructure() {} + protected GraphSaveStructure(Graph graph) { + vertices = graph.vertices(); + edges = graph.edges(); } + + public Collection vertices; + public Collection> edges; } // TODO maybe -> STATIC saveOnFile(orString) INSTANCE loadFromFile(orString), but need JSON parser