首页 > 解决方案 > 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);

    }

}

这将打印出空列表“[]”。

标签: javalistarraylistdeep-copyshallow-copy

解决方案


尝试将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);

推荐阅读