Lewis
Lewis

Reputation: 175

java add object to arrayList

I read most of the other things on SO and I couldn't seem to find an answer.

  1. Don't know how to write an add method. I'm getting a StackOverflowError. It seems to run infinitely which I am not sure why.
  2. Also, just wanted to confirm that it is possible to write a print function that prints out everything in arraylist myPolygon right?
class IrregularPolygon{
    private ArrayList <Point2D.Double> myPolygon;

   // constructors
   public IrregularPolygon() { }

   // public methods
   public void add(Point2D.Double aPoint) { 
       //System.out.println("in");
       this.add(aPoint);
       System.out.println("finished");

//     for (Point2D.Double number : myPolygon) {
//         System.out.println("Number = " + aPoint);
//     }  
   }
}


public class App{
    public static void main(String[] args){
        IrregularPolygon polygon = new IrregularPolygon();
        Point2D.Double point = new Point2D.Double(1.2, 2.3);
        System.out.println(point);
        polygon.add(point);   

    } // main   
} // class

Upvotes: 0

Views: 110

Answers (1)

rgettman
rgettman

Reputation: 178333

Calling this.add(aPoint) in add is a recursive call. This method calls itself, and there is no base case, so this results in a StackOverflowError once it recurses deeply enough.

It looks like you want to add it to the ArrayList, so change

this.add(aPoint);

to

myPolygon.add(aPoint);

In addition, you never initialized myPolygon, so it's null. Initialize it:

private ArrayList <Point2D.Double> myPolygon = new ArrayList<>();

Upvotes: 2

Related Questions