I use Van Emde Boas trees, and I came across a situation where using recursion in a constructor is incredibly useful.
When I create the root of the node in the tree, the node will have pointers to many other nodes, and these nodes will point to many other nodes, etc. Even if they are initialized with null data, I still want them all there.
EDIT: In response to the comment, I thought this might be bad practice, because we should always be careful when allocating memory. In this case, the user may not be aware of the effects that allocate the new one, such a node may have, and therefore they can allocate more memory than they expected? In addition, it seems to me that just allocating / dangerous allocating memory in the constructor.
The code recursively creates new nodes until a complete tree is created. Is this a bad practice? If this is the best way to do this in Java?
//Constructor public VEBNode(int universeSize) { this.universeSize = universeSize; min = vEBTree.NULL; max = vEBTree.NULL; if(universeSize <= 2) { summary = null; cluster = null; } else { int childUnivereSize = (int)Math.sqrt(universeSize); summary = new VEBNode(childUnivereSize); cluster = new VEBNode[childUnivereSize]; for(int i = 0; i < childUnivereSize; i++) { cluster[i] = new VEBNode(childUnivereSize); } } }
source share