我在渲染Jung图时遇到问题-该图由于某种原因正在创建重复节点。

我加载节点(将两种不同的类型加载到自定义Vertex类中(MovieVertex扩展RootNode实现NodeInfo,而PersonVertex扩展RootNode实现NodeInfo)-RootNode具有一个名称字段,我使用以下代码在顶点标签上显示该字段:

      DirectedSparseGraph<NodeInfo,String> g = new DirectedSparseGraph<NodeInfo, String>();
// Code to read node data from a Neo4j graph database
      List<Map<String, Object>> nodes = grapher.read(cql);

      try (Session session = grapher.driver.session()){
             StatementResult result = session.run(cql2);
                while (result.hasNext()) {
                  Record record = result.next();
                  String targetNode = record.get(1).get("title").toString();
                  String sourceNode = record.get(0).get("name").toString();
                  String tagline = record.get(1).get("tagline").toString();
                  String released = record.get(1).get("released").toString();
                  int born = record.get(0).get("born").asInt();
                  String rel = sourceNode + "-ACTED_IN-"+ targetNode;
                  //The problem is probably here - it is creating duplicate vertices for the same data
                 MovieVertex mv = new MovieVertex(targetNode,tagline,released);
                 PersonVertex pv = new PersonVertex(sourceNode,born);
                  g.addVertex(pv);

                  g.addVertex(mv);
                  g.addEdge(rel, pv, mv);
                  ISOMLayout<NodeInfo,String> layout = new ISOMLayout<NodeInfo,String>(g);

                VisualizationViewer<NodeInfo,String> vv =
          new VisualizationViewer<NodeInfo,String>(layout, new Dimension(800,800));

                vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
               JFrame frame = new JFrame();
               frame.getContentPane().add(vv);
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               frame.pack();
               frame.setVisible(true);
            }


java - 在JUNG图中创建冗余重复节点-LMLPHP
编辑:我将以下代码添加到Vertex自定义类中,以解决该问题,并更新了图形示例:

    @Override
    public boolean equals(Object o) {

        if (o == this) return true;
        if (!(o instanceof MovieVertex)) {
            return false;
        }

        MovieVertex mv = (MovieVertex) o;

        return new EqualsBuilder()
                .append(title, mv.title)
                .append(tagline, mv.tagline)
                .append(released, mv.released)
                .isEquals();
    }

  @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(title)
                .append(tagline)
                .append(released)
                .toHashCode();
    }


java - 在JUNG图中创建冗余重复节点-LMLPHP

最佳答案

这是用作Map密钥的任何自定义Java类的常见问题(就像JUNG Vertices一样)。除非您在自定义Vertex类中重写equalshashCode方法,否则将得到重复项。如果将MovieVertexPersonVertex实例添加到java.util.Set或将它们用作Map中的键,则会遇到相同的问题。
也许您可以使用名称字段来计算hashCode的值并确定顶点何时相等。

09-27 11:47