Home > Software engineering >  In Dart, how can copy/clone a 2D list?
In Dart, how can copy/clone a 2D list?

Time:09-27

I have 2 two dimensional lists declared as following, what is the correct and fast way to copy/clone a 2 dimensional list (I to N) in Dart?

List<List<double>>? I = List.generate(
        3, (i) => List.generate(1000 * 1000, (j) => 0.0, growable: false),
        growable: false);
 List<List<double>>? N = List.generate(
        3, (i) => List.generate(1000 * 1000, (j) => 0.0, growable: false),

I can loop through each element and copy it but that's not the efficient way to do it.

for (int i = 0; i < I!.length; i  )
      for (int j = 0; j < I![i].length; j  ) N![i][j] = I![i][j];

CodePudding user response:

List List.copyRange(List target, int at, List source, [int? start, int? end])

list.setRange(int start, int end, Iterable iterable, [int skipCount = 0])

for (int i = 0; i < I!.length; i  )
    List.copyRange<int>(N![i], 0, I![i])
for (int i = 0; i < I!.length; i  )
    N![i].setRange<int>(0, N![i].length,I![i])

This will reset the item pointer

List.copyRange(N!,0, I!.map<List<int>>((item)=>item.toList());

CodePudding user response:

Given a List<List<double>> named original, I would copy it with:

List<List<double>> copy = [for (var sublist in original) [...sublist]];

Note that this would create a new List<List<double>>; if you must mutate an existing one instead, then using List.setRange as shirne suggested would be more appropriate.

  • Related