2
    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));
}

Except using for loop to do hard copy for every inner list, do we have another way to do hard copy. Could you explain how List<List<Integer>> ll2 = new ArrayList<List<Integer>>(ll1); work and why it fail?

cow12331
  • 245
  • 2
  • 3
  • 9

1 Answers1

1

You also need to copy the inner lists:

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;
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118