I want to make each line read from the csv as a sub_list and add such sub_list to a master_list.
so it would be something like:
[[line 1] [line 2] ....[last line]]
How to make sure the sub_list added in the master_list is not affected by the changes in the original sub_list. I understand it's something to do with shallow vs deep copy. What is the correct way to do it. The reason for doing in this way is because I might use the sublist for other different operations elsewhere. once I need to do so, I need to clear the content inside it as an empty list. Hence I want to maintain the use of the same list for different tasks.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CSVReader {
public static void main(String[] args) {
String csvFile = "E:\\country.csv";
String line = "";
String cvsSplitBy = ",";
List<String> sub = new ArrayList<String>();
List<List> master = new ArrayList<List>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
sub.add(line);
master.add(sub);
// System.out.println(sub);
sub.remove(0);
// System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(master);
}
}
this prints out empty list "[]".
>`, you can use two dimention array `String[][]`
– Eugen Sep 29 '19 at 06:48