java - Creating linked list parsing line trouble -
i reading lines file, total number around 150,000 lines. each time line read
-i modify object city,
-then add linked list
-then print out content of linked list in last position, , find correct.
-after filereader loop ends, find object on linkedlist have same city value, last value entered ( last line of file read) --> problem
public static void lala() throws ioexception{ string fileline; bufferedreader r = new bufferedreader(new filereader( "list_of_1000_cities 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 correct name } } system.out.println(citylist.get(1115).name); // prints last name on file read no matter how change index printed }
java refers objects references. hence within while loop modifying value of same reference x have assigned outside loop.
instantiate new value of x within while loop each of co-ordinates , add list - problem solved.
to more specific code :
string fileline;
bufferedreader r = new bufferedreader(new filereader( "list_of_1000_cities 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 correct name } } system.out.println(citylist.get(1115).name);
Comments
Post a Comment