我试图用从代表点的文本文件中读取整数(每行两个整数)创建的对象填充 arrayList。我正在尝试循环执行此操作。ArrayList 似乎填满了,但是当我打印出来之后,每个索引中的所有元素都与添加到 ArrayList 的最后一个元素相同。这似乎与指向对象的每个 arrayList 索引有关(我的新手猜测)。我必须为每个 arrayList 条目创建一个唯一的对象吗?有没有一种简单的方法可以添加到此代码中来做到这一点?
public class Point2DDemo extends Point2D<Double>
{
ArrayList<Point2DDemo> Points = new ArrayList<Point2DDemo>(7);
/**
* Constructor for objects of class Point2DDemo
*/
public Point2DDemo()
{
}
public Point2DDemo(double first, double second)
{
setFirst(first);
setSecond(second);
}
public void putPair(double point1, double point2){
this.setFirst(point1);
this.setSecond(point2);
}
/**
*
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public void createList()
{
FileIO readFile = new FileIO();
readFile.openInputFile();
String pointLine = null;
Point2DDemo newPoints = new Point2DDemo();
StringTokenizer stringSplit = null;
while(readFile.hasInputLine())
{
pointLine = readFile.readInputLine();
stringSplit = new StringTokenizer(pointLine);
double pointX = Double.parseDouble(stringSplit.nextToken());
double pointY = Double.parseDouble(stringSplit.nextToken());
newPoints.putPair(pointX, pointY);
Points.add(newPoints);
}
for(int i = 0; i < Points.size(); i++)
System.out.println(Points.get(i));
readFile.closeInputFile();
}