简体   繁体   中英

OutOfMemoryError when trying to add elements from a B+Tree to an ArrayList

I'm attempting to traverse through a B+ Tree and add the elements from the leaves into an ArrayList with the following code:

public void toArrayList(Node node){
       Node currentNode = node;
       if(currentNode instanceof InnerNode){
               InnerNode inner = (InnerNode) currentNode;
               int i = 0;
               int temp = inner.children.length;
               while(i < temp){
                   currentNode = inner.children[i];
                   toArrayList(currentNode);
                   i++;
               }


           }
       if(currentNode instanceof LeafNode){
               LeafNode leaf = (LeafNode) currentNode;
               int j = 0;
               int temp = leaf.values.length;
               while(j < temp){
                   if(leaf.values[j] != null) {
                       retArray.add(leaf.values[j]);
                   }
                   j++;
               }

           }
    }

What it does is it checks if the node is an instance of an Inner Node or a Leaf Node. If it is an Inner Node it recursively calls the function with each of its children. If it is a Leaf Node then it will add the values into the ArrayList. However while running this fucntion I end up getting a java.lang.OutOfMemoryError .

Is there a way to make my code more efficient or should I look to take a different approach to this method?

Unless your tree structure has a few million elements in it, what's going on here is that some InnerCode contains itself, and thus this code keeps going forever, or, at least, until your retArray fills up.

Also note that this code will add a leaf node twice if it's the last child of an inner node. I strongly suggest you don't overwrite locals like this. Also, for loops are just more compact here (note that making this code smaller is not going to make any difference at all for memory issues; OOMError refers to the heap, and locals don't live there).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM