user1022241
user1022241

Reputation:

Traversing a deep data structure & deleting object

I have a function to traverse a complex deep HashMap structure. My problem is that when I find the desired node, and do any action on it, such as deleting it, I'm not actually doing any action on the data structure, but instead I'm operating on a copy of the data structure. I'd think a pointer such as in C++ would solve my problem, so how can I do this in Java?

The code:

private HashMap parentNode = null;
// a complex JSON string of arrays / objects, won't list for brevity
private String jsonString = ...
// parses JSON string into HashMaps for objects and Object[ ]s for arrays
private HashMap arr = (HashMap)JSON.parse(jsonString);
// find the node with an id of 27
HashMap parent = findNode(arr, "27");
// Print arr before modifying node
System.out.println(arr);
// modify parent in some way
parent = null;    
// Print arr after modifying node
System.out.println(arr);

public HashMap findNode(HashMap map, String id) {
    parentNode = null;
    findNodeRecursive(map, id);
    return parentNode;
}

public void findNodeRecursive(HashMap map, String id) {
    for(Object entry : map.entrySet()){
        Object value = ((Map.Entry)entry).getValue();
        if((value instanceof String) && ((String)value).equals(id))
            parentNode = map;
        else if(value instanceof HashMap)
            findNodeRecursive((HashMap)value,id);
        else if(value instanceof Object[])
            for(int i=0; i<((Object[])value).length; i++)
                findNodeRecursive( (HashMap)(((Object[])value)[i]) ,id);
    }
}

Upvotes: 2

Views: 225

Answers (1)

Jose Rui Santos
Jose Rui Santos

Reputation: 15319

To delete the node you want (parent), change your

parent = null;

to

arr.remove(parent);

Setting it to null does not delete anything, simply changes the reference that once was pointing to the node, back to null. To delete, you need to do it explicitly by using the HashMap.remove() method

Upvotes: 2

Related Questions