优雅的方式来检查节点是否已经在图中

时间:2015-09-29 11:39:33

标签: java loops graph

我想检查具有特定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

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

1 个答案:

答案 0 :(得分:5)

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

但一般情况下,只需保留从portIds到节点的地图 如果您想进行检查,请查阅该地图 这将更容易,更快捷。

相关问题