Dart: List of Lists

2020-02-01 15:41发布

问题:

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

PS: it's not a mental exercise only.

回答1:

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.



回答2:

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]]


标签: list dart