如何在DefaultDirectedGraph或JGraphT中表征边?是否需用映射关联边与对象?
给JGraphT有向图的边添加友谊信息的两种方案
嘿,针对你用DefaultDirectedGraph创建有向图、想给边存储学生友谊信息的需求,我整理了两种实用的方案,你可以根据自己的场景选择:
方案一:自定义带属性的边类(推荐)
DefaultEdge本身只是个基础的边实现,没有额外的属性字段。最直接的方式是自定义一个继承自DefaultEdge的边类,把友谊相关的信息(比如建立时间、亲密度、备注等)作为属性加进去。
举个具体的代码例子:
// 自定义友谊边类,继承DefaultEdge并添加属性 public class FriendshipEdge extends DefaultEdge { private LocalDate friendshipStartDate; private int closenessScore; // 比如1-10的亲密度评分 // 构造方法 public FriendshipEdge(LocalDate startDate, int score) { this.friendshipStartDate = startDate; this.closenessScore = score; } // Getter方法,用于获取属性 public LocalDate getFriendshipStartDate() { return friendshipStartDate; } public int getClosenessScore() { return closenessScore; } }
然后创建图的时候,指定这个自定义边类:
// 泛型指定顶点类型(你的学生对象)和自定义边类型 DefaultDirectedGraph<Student, FriendshipEdge> graph = new DefaultDirectedGraph<>(FriendshipEdge.class);
添加边的时候,直接传入FriendshipEdge对象:
Student alice = new Student("Alice"); Student bob = new Student("Bob"); graph.addVertex(alice); graph.addVertex(bob); // 添加带友谊信息的边 graph.addEdge(alice, bob, new FriendshipEdge(LocalDate.of(2023, 1, 1), 8));
后续想要获取边的友谊信息时,直接从边对象里拿就行,不用额外维护映射,代码逻辑更清晰,也符合面向对象的设计思路。
方案二:用映射关联边和友谊对象
如果暂时不想修改边的类型,或者有其他限制,也可以用一个Map来保存边对象和友谊信息对象的对应关系。
示例代码:
// 原有的图定义 DefaultDirectedGraph<Student, DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class); // 创建映射,存储边到友谊信息的关联 Map<DefaultEdge, FriendshipInfo> edgeFriendshipMap = new HashMap<>(); // 添加顶点和边 Student alice = new Student("Alice"); Student bob = new Student("Bob"); graph.addVertex(alice); graph.addVertex(bob); // 添加边后,把边和友谊信息关联起来 DefaultEdge edge = graph.addEdge(alice, bob); edgeFriendshipMap.put(edge, new FriendshipInfo(LocalDate.of(2023, 1, 1), 8));
这种方式的优点是不用修改现有图的定义,但缺点也很明显:需要额外维护这个映射,当图里的边被删除时,要记得同步删除映射里的对应条目,否则容易出现数据不一致的问题。
内容的提问来源于stack exchange,提问作者Mina Nabi
相关产品推荐
相关产品推荐

