我在渲染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);
}
编辑:我将以下代码添加到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();
}
最佳答案
这是用作Map
密钥的任何自定义Java类的常见问题(就像JUNG Vertices一样)。除非您在自定义Vertex类中重写equals
和hashCode
方法,否则将得到重复项。如果将MovieVertex
或PersonVertex
实例添加到java.util.Set
或将它们用作Map中的键,则会遇到相同的问题。
也许您可以使用名称字段来计算hashCode的值并确定顶点何时相等。