Solved

Adding element to a Vector causes StackOverflowError

Posted on 2007-04-03
2
166 Views
Last Modified: 2013-11-23
Hi,
I get a 'Stack overflow error:null' with the below code (relevant bits posted below) when adding an instance of class AClass

to a Vector. Does anyone know what's causing this, please help...

java.lang.StackOverflowError
      at AClass.addTank(AClass.java:25)
      at AClass.<init>(AClass.java:19)
      at AClass.addTank(AClass.java:25)
      at AClass.<init>(AClass.java:19)
      at AClass.addTank(AClass.java:25)
      at AClass.<init>(AClass.java:19)

Tonnes more of these

import java.util.Vector;

   public static Vector AClasss = new Vector();

    public AClass()
    {
        setX(targetX);
        setY(targetY);
        addTank();      //Line 19
        start();
    }


    public void addTank()
    {
        AClass AClass = new AClass();      //Line 25
        AClasss.addElement(AClass);         //Add the new instance to the vector
    }
0
Comment
Question by:mark_667
2 Comments
 
LVL 14

Accepted Solution

by:
CPColin earned 125 total points
ID: 18846834
The way you have it now, addTank() creates a new AClass object, but the constructor for AClass calls addTank(), which traps it in an endless loop until the Java VM runs out of space and gives up. Either you need to take the addTank() call out of the constructor, or the "new AClass()" line out of addTank().
0
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 18848344
Line 25 - create a different object than AClass. Try with something like:

Integer x = new Ineteger(10);
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
The viewer will learn how to implement Singleton Design Pattern in Java.

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question