Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle a List of Lists?

Tags:

list

dart

Could someone explain what goes wrong in this piece of code? From the code one (at least myself) would expect that after having ran this code the number list would look like numbers = [[0], [1]], but instead it looks like numbers= [[0,1], [0,1]].

void main() {
  int n = 2;
  List<List<int>> numbers = new List.filled(n, []);
  
  for(int i=0; i<n; i++)
    for(int j=i+1; j<n; j++ ){
      numbers[i].add(0);
      numbers[j].add(1);
    }
}
like image 756
Victor Ermolaev Avatar asked Nov 29 '22 15:11

Victor Ermolaev


2 Answers

It seems each element of your list is filled with the same instance of []. If you then do numbers[0].add(0); numbers[0] and numbers[1] show the added 0 because they reference the same list instance.

Changing the list initialization to

List<List<int>> numbers = new List.generate(n, (i) => []);

Shows your expected behavior.

like image 90
Günter Zöchbauer Avatar answered Dec 05 '22 00:12

Günter Zöchbauer


I had the same problem, and was helped by Günter Zöchbauers answer. However, to get proper control over "width" of the "array" I adjusted the code like this:

List <List<num>> graphArray = new List.generate(arrayMaxY, (i) => new List(arrayMaxX));

When arrayMaxY=3 and arrayMaxX=2, the result is:

[[null, null], [null, null], [null, null]]

What was crucial for me was that the methods List.first and List.last worked on my "array", and they do with this constructor. Also, this now works as intended:

graphArray[1][0] = 42;
print(graphArray); // [[null, null], [42, null], [null, null]]
like image 20
Yngvar Natland Avatar answered Dec 05 '22 02:12

Yngvar Natland