Vector <Point2D> .add()替换所有现有元素以及附加

Ota*_*our 0 java

我正在使用NetBeans 7.3.1上的java SE进行开发

我正在尝试读取CSV文件每行的前两个元素,将它们输入Point2D类型的点变量,并将每个点附加到Point2D矢量坐标的末尾.我使用以下代码.

br = new BufferedReader(new FileReader(inputFileName));

Vector<Point2D> coords = new Vector<Point2D>();
Point2D newPoint=new Point2D.Double(20.0, 30.0);
while ((strLine = br.readLine()) != null){
     String [] subStrings = strLine.split(" ");
     System.out.print("Substrings = " + subStrings[0] + ", " + subStrings[1]);
     System.out.println();
     newPoint.setLocation(Float.parseFloat(subStrings[0]), Float.parseFloat(subStrings[1]));
     coords.add(newPoint);          
}
Run Code Online (Sandbox Code Playgroud)

coords.add(newPoint); 根据需要附加点,但它也会用新点替换coords中的每个现有元素.如何阻止现有元素被新元素替换?

Syo*_*yon 7

每个Point2D值的变化原因coords是因为Vector中只有一个对象,你只是重复地将它添加到Vector中.当您调用时,setLocation您正在更新该单个对象,并且它会反映在Vector中包含的对象的每个引用中.

每次要添加其他条目时,都需要创建一个新的Point2D coords.

更改

newPoint.setLocation(Float.parseFloat(subStrings[0]), Float.parseFloat(subStrings[1]));
Run Code Online (Sandbox Code Playgroud)

newPoint=new Point2D.Double(Float.parseFloat(subStrings[0]), Float.parseFloat(subStrings[1]));
Run Code Online (Sandbox Code Playgroud)