I am trying to fill an arrayList with objects created from reading integers from a text file that represent points (two integers per line). I'm attempting to do this in a loop. The ArrayList seems to fill, but when I print it out after, all the elements in each index are the same as the last element added to the ArrayList. This seems to have something to do with each arrayList index pointing to the object (my newbie guess). Do I have to create a unique object for each arrayList entry? Is there an easy way to add to this code to do this?
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();
}