Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6552719
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T12:29:40+00:00 2026-05-25T12:29:40+00:00

I’m attempting to implement a binary tree for an Android app, and I want

  • 0

I’m attempting to implement a binary tree for an Android app, and I want to be able to serialize it to a file on the device. Unfortunately, I’m getting stackoverflow errors when trying to serialize it.

Code:

class BTree<V extends Model> implements Serializable {
/**
 * 
 */
private static final long serialVersionUID = 4944483811730762415L;

private V value;
private BTree<V> left;
private BTree<V> right;

public BTree(V value) {
    this.value = value;
}

public BTree(V value, BTree<V> left, BTree<V> right) {
    this.value = value;
    this.left = left;
    this.right = right;
}

private int getValue() {
    return this.value.hashCode();
}

public void insert(BTree<V> node) {     
    if (this.getValue() >= node.getValue()) {
        if (this.left == null) {
            this.left = node;
        } else {
            this.left.insert(node);
        }
    } else {
        if (this.right == null) {
            this.right = node;
        } else {
            this.right.insert(node);
        }
    }
}

public boolean containsKey(Object key) {
    return this.find(key) != null;
}

public V find(Object key) {
    if (key.hashCode() == this.getValue()) {
        return this.value;
    } else if (key.hashCode() > this.getValue() && this.left != null) {
        return this.left.find(key);
    } else if (key.hashCode() < this.getValue() && this.right != null) {
        return this.right.find(key);
    } else {
        return null;
    }
}

public ArrayList<V> getAllValues() {
    ArrayList<V> values = new ArrayList<V>();
    if (this.left != null) {
        values.addAll(this.left.getAllValues());
    }
    if (this.right != null) {
        values.addAll(this.right.getAllValues());
    }

    return values;
}
}

And I’m trying to serialize in this block of text in a separate class:

try {           
        FileOutputStream fos = this.context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(this.tree);
        oos.close();

        //this.lastModified = getLastModified(FILE_NAME);
    } catch (FileNotFoundException e) {
        //File will get created, so this doesn't matter
    } catch (IOException e) {
        Log.d("BTreeModel Serialization Error", "Error serialization model.");
        Log.e("Serialization error details", e.toString());
    } 

What I have noticed is that if I serialize to a file that does not currently exist, the it serializes fine. The second time I run the same program it causes the StackOverflowException when serializing to disk again.

Here is the output of logcat:

09-07 05:29:42.011: ERROR/AndroidRuntime(916): FATAL EXCEPTION: main
09-07 05:29:42.011: ERROR/AndroidRuntime(916): java.lang.StackOverflowError
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at         java.util.IdentityHashMap.getModuloHash(IdentityHashMap.java:435)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.util.IdentityHashMap.findIndex(IdentityHashMap.java:419)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at     java.util.IdentityHashMap.get(IdentityHashMap.java:371)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.dumpCycle(ObjectOutputStream.java:471)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1739)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1689)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1653)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:1143)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:413)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1241)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1205)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1575)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1847)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1689)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1653)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:1143)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:413)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1241)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1575)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1847)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1689)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1653)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:1143)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:413)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1241)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1575)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1847)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1689)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1653)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:1143)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:413)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1241)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1575)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1847)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1689)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1653)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:1143)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:413)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1241)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1575)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1847)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1689)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1653)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:1143)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:413)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1241)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1575)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1847)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1689)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1653)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:1143)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:413)
09-07 05:29:42.011: ERROR/AndroidRuntime(916):     at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.j

From the Activity that adds the nodes:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //TextView averageHashMapTime = (TextView)findViewById(R.id.averageHashCollectionTime);
    //averageHashMapTime.setText("Just a moment");
    //TextView averageBtreeTime = (TextView)findViewById(R.id.averageBTreeCollectionTime);
    //averageBtreeTime.setText("working");

    HashMapModelCollection<Integer, Content> hashCollection = new HashMapModelCollection<Integer, Content>(this);
    long totalTicks = 0;
    final int totalIterations = 16;

    BTreeModelCollection<Integer, Content> btreeCollection = new BTreeModelCollection<Integer, Content>(this);
    totalTicks = 0;
    for(int i = 0; i < totalIterations; i++) {
        Content test = new Content();
        test.setText(String.valueOf(i));
        Random r = new Random();
        int key = r.nextInt();
        Date start = new Date();
        btreeCollection.put(key, test);
        Date end = new Date();

        totalTicks += end.getTime() - start.getTime();
    }

    Log.d("Finished", "btree length: " + String.valueOf(totalTicks / totalIterations));
    Toast.makeText(this, "btree length: " + String.valueOf(totalTicks / totalIterations), Toast.LENGTH_LONG).show();
    //averageBtreeTime.setText(String.valueOf(totalTicks / totalIterations));

}

The class that directly handles the BTree objects:

public class BTreeModelCollection<K extends Serializable, V extends Model> implements IModelCollection<K, V>,
    Serializable {


/**
 * 
 */
private static final long serialVersionUID = -3969909157515987705L;

private static final String FILE_NAME = "testCollection-5";

private BTree<V> tree;
private Context context;

public BTreeModelCollection(Context context) {
    this.context = context;
}

@Override
public void clear() {
    // TODO Auto-generated method stub

}

@Override
public boolean containsKey(Object key) {
    return tree.containsKey(key);
}

@Override
public boolean containsValue(Object value) {
    // TODO Auto-generated method stub
    return false;
}

@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public V get(Object key) {
    return getTree().find(key);
}

@Override
public boolean isEmpty() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public Set<K> keySet() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void put(K key, V value) {
    value.setKey(key);
    getTree();
    if (this.tree != null) {
        this.tree.insert(new BTree<V>(value));
    } else {
        this.tree = new BTree<V>(value);
    }
    serialize();
}

@Override
public V remove(Object key) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int size() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public Collection<V> values() {
    return getTree().getAllValues();
}

@Override
public void putAll(Map<? extends K, ? extends V> map) {
    // TODO Auto-generated method stub

}

private BTree<V> getTree() {
    if (this.tree == null) {
        loadTree();
    }

    return tree;
}

@SuppressWarnings("unchecked")
private void loadTree() {
    try {
        FileInputStream fis = context.openFileInput(FILE_NAME);
        ObjectInputStream ois = new ObjectInputStream(fis);
        this.tree = (BTree<V>)ois.readObject();
        ois.close();
    } catch (FileNotFoundException e) {
        this.tree = null;
    } catch (StreamCorruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        this.tree = null;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } 
}

private void serialize() {
    if (this.tree == null) {
        Log.w("Serialization problem", "No collection to serialize to disk");
        return;
    }

    try {           
        FileOutputStream fos = this.context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(this.tree);
        oos.close();

        //this.lastModified = getLastModified(FILE_NAME);
    } catch (FileNotFoundException e) {
        //File will get created, so this doesn't matter
    } catch (IOException e) {
        Log.d("BTreeModel Serialization Error", "Error serialization model.");
        Log.e("Serialization error details", e.toString());
    } 
}

}

And the Model class:

public abstract class Model implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = -5724152403115334006L;

private Serializable key;

void setKey(Serializable key) {
    this.key = key;
}

Serializable getKey() {
    return this.key;
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T12:29:40+00:00Added an answer on May 25, 2026 at 12:29 pm

    Here is the code for the revised class that solves the StackOverflowException problem. It does have one critical drawback: For unbalanced trees, it is incredibly inefficient as it has to resize the internal array over and over.

    class BTree<V extends Model> implements Serializable {  
    /**
     * 
     */
    private static final long serialVersionUID = -7602392759811243945L;
    
    private static final int MINIMUM_CAPACITY = 15;
    
    private Model[] values;
    private int depth = 3;
    
    public void insert(V newValue) {    
        int index = 0;
        while(true) {           
            ensureSpotExists(index);
    
            Model value = values[index];
            if (value == null) {                
                values[index] = newValue;
                return;
            } else if (newValue.getKey().hashCode() < value.getKey().hashCode()) {
                index = (2 * index) + 1;
            } else if (newValue.getKey().hashCode() > value.getKey().hashCode()) {
                index = (2 * index) + 2;
            } else {
                values[index] = newValue;
                return;
            }
        }
    }
    
    protected void ensureSpotExists(int index) {
        if (this.values == null) {
            this.values = new Model[MINIMUM_CAPACITY];
        } else if (this.values.length < index + 1) {
            Model[] temp = this.values;
            this.values = new Model[getSize(++depth)];
            for(int i = 0; i < temp.length; i++) {
                this.values[i] = temp[i];
            }
        }
    }
    
    protected static int getSize(int depth) {
        int size = 0;
        for(int i = 0; i <= depth; i++) {
            size += Math.pow(2, i);
        }
    
        return size;
    }
    
    public boolean containsKey(Object key) {
        return this.find(key) != null;
    }
    
    public V find(Object key) {
        return null;
    }
    
    void replace(Object key, V value) {
        return;
    }
    
    public List<Model> getAllValues() {
        return Arrays.asList(this.values);
    }  
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want use html5's new tag to play a wav file (currently only supported
i want to parse a xhtml file and display in UITableView. what is the
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I want to construct a data frame in an Rcpp function, but when I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.