java - Java:将一个列表添加到另一个列表而不复制引用
问题描述
我想让从 csv 中读取的每一行作为 sub_list 并将这样的 sub_list 添加到 master_list。
所以会是这样的:</p>
[[第 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);
}
}
这将打印出空列表“[]”。
解决方案
尝试将sub
变量声明移动到 while 块上。
String csvFile = "E:\\country.csv";
String line = "";
String cvsSplitBy = ",";
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);
List<String> sub = new ArrayList<String>();
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);
推荐阅读
- docker - 使用带有等待的 Dockerfile 执行两个命令
- laravel - 如何一次将数据发送到多个通道?(laravel,广播)
- api - 通过 swagger 提供二进制 API 文档
- mysql - Mysql查询日志(查询结果)
- c++ - 带有自定义设置比较器的 set_intersection
- c++ - C++:从 GPU 内存 (cudaMemcpy2D) 获取 BGR 图像 (cv::Mat)
- bash - 在 bash elif (FreeNAS) 中组合两个命令
- python - 如何从 shapely.geometry.Polygon 获取 matplotlib.path.Path 对象?
- python - Websocket客户端未收到任何消息
- php - 如何从 WooCommerce 变体选项卡中删除“切换可下载”