2015-09-29 34 views
0

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

事實上,我正在創建一個只是佔位符的虛擬節點真的很醜。請讓我知道如何以更優雅的方式解決這個問題。

回答

5

好吧,你可以做到這一點Node node = null;

但在一般情況下,只要繼續從該端口ID到節點的映射。
當你想進行檢查時,只需查看該地圖即可。
它會更方便,更快捷。

+1

「不要設置標誌;設置數據。」 - 'alreadyCreated'可以被刪除,因爲檢查一個空節點就足夠了。 –

相關問題