我正在使用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);
}
coords.add(newPoint);根据需要附加点,但它也会用新点替换coords中的每个现有元素。如何阻止现有元素被新元素替换?
答案 0 :(得分:7)
coords
中每个Point2D的值更改的原因是因为Vector中只有一个对象,您只是重复将它添加到Vector中。当您调用setLocation
时,您正在更新该单个对象,并且它反映在对Vector中包含的对象的每个引用中。
每次要将另一个条目添加到coords
时,您需要创建一个新的Point2D。
更改
newPoint.setLocation(Float.parseFloat(subStrings[0]), Float.parseFloat(subStrings[1]));
到
newPoint=new Point2D.Double(Float.parseFloat(subStrings[0]), Float.parseFloat(subStrings[1]));