【问题标题】:How to hard copy List<List<>> in java?如何在 java 中硬拷贝 List<List<>>?
【发布时间】:2015-01-11 15:58:07
【问题描述】:
    public static void main(String[] args) {
     List<List<Integer>> ll1 = new ArrayList<List<Integer>>();
     ll1.add(new ArrayList<Integer>(1));
     System.out.println(ll1.get(0));
     //hard copy don't work
     List<List<Integer>> ll2 = new ArrayList<List<Integer>>(ll1);
     System.out.println(ll2.get(0) == ll1.get(0));
}

除了使用 for 循环对每个内部列表进行硬拷贝之外,我们是否还有另一种方式来进行硬拷贝。 您能解释一下List&lt;List&lt;Integer&gt;&gt; ll2 = new ArrayList&lt;List&lt;Integer&gt;&gt;(ll1); 的工作原理以及失败的原因吗?

【问题讨论】:

    标签: java list copy


    【解决方案1】:

    您还需要复制内部列表:

    private List<List<Integer>> copy(List<List<Integer>> toCopy) {
        List<List<Integer>> copy = new ArrayList<>(toCopy.size());
        for(List<Integer> inner : toCopy) {
            copy.add(new ArrayList<Integer>(inner));
        }
        return copy;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-12
      • 2018-10-05
      • 2021-01-07
      • 2015-04-27
      • 2020-03-01
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多