[英]java add object to arrayList
I read most of the other things on SO and I couldn't seem to find an answer. 我在SO上阅读了其他大部分内容,但似乎找不到答案。
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
Calling this.add(aPoint)
in add
is a recursive call. 在
add
调用this.add(aPoint)
是一个递归调用。 This method calls itself, and there is no base case, so this results in a StackOverflowError
once it recurses deeply enough. 此方法会自我调用,并且没有基本情况,因此一旦深度递归,就会导致
StackOverflowError
。
It looks like you want to add it to the ArrayList
, so change 看起来您想将其添加到
ArrayList
,所以更改
this.add(aPoint);
to 至
myPolygon.add(aPoint);
In addition, you never initialized myPolygon
, so it's null
. 此外,您从未初始化
myPolygon
,因此它为null
。 Initialize it: 初始化它:
private ArrayList <Point2D.Double> myPolygon = new ArrayList<>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.