我想将从 csv 中读取的每一行作为 sub_list 并将此类 sub_list 添加到 master_list 中。
所以它会是这样的:
[[第 1 行] [第 2 行] ....[最后一行]]
如何保证master_list中添加的sub_list不受原sub_list变化的影响。我知道这与浅复制和深复制有关。正确的做法是什么。这样做的原因是因为我可能会在其他地方使用子列表进行其他不同的操作。一旦我需要这样做,我需要将其中的内容清除为空列表。因此,我想对不同的任务使用相同的列表。
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);
}
}
这会打印出空列表“[]”。
qq_遁去的一_1
白板的微信
幕布斯7119047
相关分类