gpt4 book ai didi

java - 检查节点是否已在图中的优雅方法

转载 作者:行者123 更新时间:2023-12-01 16:56:01 24 4
gpt4 key购买 nike

我想检查具有特定 ID 的节点是否已存在于我的图中,或者我是否必须创建一个新对象。目前我正在使用以下代码执行此操作:

// at this point I have the attributes for the node I need

String id = getIdOfNeededNode(); // The id is used to search for the node in the graph

// now I have to search for the node in the graph
Node node = new Node("dummy_id"); // This is the line I don't like;
// I would prefer not to have a dummy node
// but the compiler will then complain that the node might not be initialized

boolean alreadyCreated = false;

for(Node r : graph.getVertices()){ // search for the node with this id in the graph
if (r.getId().equals(portId)){
node = r;
alreadyCreated = true;
break;
}
}

if (!alreadyCreated) { // create a new object if the node was not found
node = new Resource(portId);
createdPortResources.add(port);
}

// In the remainder of the program, I am working with the node object which then is in the graph

事实上,我正在创建一个只是占位符的虚拟节点,这真的很难看。请让我知道如何以更优雅的方式解决这个问题。

最佳答案

好吧,你可以这样做 Node node = null;

但一般来说,只需保留从 portId 到节点的映射即可。
当您想要进行检查时,只需查阅该 map 即可。
这将变得更加容易和快捷。

关于java - 检查节点是否已在图中的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32842965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com