2015-09-29 2 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;

Но в общем, просто держать карту от portIds к узлам.
Если вы хотите сделать эту проверку, просто проконсультируйтесь с этой картой.
Это будет проще и быстрее.

+1

«Не устанавливайте флаг, установите данные». - 'readyCreated' можно удалить, так как проверка нулевого узла достаточно. –

Смежные вопросы