我正在从文件中读取行,总数约为 150,000 行。每次读取一行
-i修改对象城市,
-然后添加到链表
-然后打印出链表最后一个位置的内容,我发现是正确的。
-filereader循环结束后,我发现链表上的所有对象都有相同的城市值,这是最后输入的值(读取文件的最后一行)-->这就是问题
public static void lala() throws IOException{
String FileLine;
BufferedReader R = new BufferedReader(new FileReader(
"list_of_1000_cities with coords.txt"));
city x = new city() ;
while ((FileLine = R.readLine()) != null) {
String[] Tokens = FileLine.split(",");
if (Preprocessor.get_double(Tokens[1])!=0 && Preprocessor.get_double(Tokens[2])!=0) {
x.latitude= Double.parseDouble(Tokens[1]);
x.longitude= Double.parseDouble(Tokens[2]);
x.name= Tokens[0];
citylist.add(x );
System.out.println(citylist.get(citylist.size() - 1).name);
//prints the correct name
}
}
System.out.println(citylist.get(1115).name);
// always prints the last name on the file read no matter how much i change the index printed
}
最佳答案
Java 通过引用来引用对象。因此,在 while 循环中,您正在修改在循环外部分配的对 X 的相同引用的值。
在 while 循环中为每个坐标实例化一个新的 X 值,然后将其添加到列表中 - 您的问题将得到解决。
要更具体地说明您的代码:
字符串文件行;
BufferedReader R = new BufferedReader(new FileReader(
"list_of_1000_cities with coords.txt"));
while ((FileLine = R.readLine()) != null) {
String[] Tokens = FileLine.split(",");
if (Preprocessor.get_double(Tokens[1])!=0 && Preprocessor.get_double(Tokens[2])!=0) {
city x = new city() ;
x.latitude= Double.parseDouble(Tokens[1]);
x.longitude= Double.parseDouble(Tokens[2]);
x.name= Tokens[0];
citylist.add(x );
System.out.println(citylist.get(citylist.size() - 1).name);
//prints the correct name
}
}
System.out.println(citylist.get(1115).name);
关于java - 创建链表解析行麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555862/