0

I'm trying to develop some tree-like data structure with Java.

class MyTree {
    private Node root;
}

class Node {
    private HashMap<Character, Node> children;
    private String content;
    // some other data members
}

As you see, each Node contains another Node, which is its children so that I can build a list like this: MyTree.root -> child1 -> child2 -> child3.

Now, if I want to delete/free this tree, can I simply do root = null; or must I loop to set each element to null? I don't know how gc exactly works in this case...

Yves
  • 11,597
  • 17
  • 83
  • 180
  • 4
    Garbage collection will free all objects which are not reachable from a "gc root". In this case you don't need to set the elements to null -- once root is null all the children are unreachable (assuming there are no other references to them) – tgdavies Oct 29 '22 at 04:49
  • @tgdavies There are no other references to them but they reference themselves as `child1 -> child2 -> ...`. Anyway, so I need only do `root = null;`. Thanks dude. – Yves Oct 29 '22 at 04:52
  • 2
    here's some more information on gc roots: https://www.yourkit.com/docs/java/help/gc_roots.jsp – tgdavies Oct 29 '22 at 04:54
  • 1
    Yes, I should have said "...no other references to them starting from a GC root" – tgdavies Oct 29 '22 at 05:03
  • @tgdavies Perhaps you can make an Answer of that useful info? – Basil Bourque Oct 29 '22 at 07:53
  • @BasilBourque it actually already mentioned here https://stackoverflow.com/questions/12242904/understanding-memory-leaks-in-java-what-are-the-classes-that-persist-through-o/12242950#12242950 (although the link had rotted, which I've just fixed) – tgdavies Oct 29 '22 at 09:04

0 Answers0