Dart:列表列表 [英] Dart: List of Lists

查看:119
本文介绍了Dart:列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释这段代码中出了什么问题吗?
从代码中(至少是我本人)期望在运行这个代码之后,数字列表看起来像 numbers = [[0],[1]] ,而是看起来像 numbers = [[0,1],[0,1]]

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:这不是一个精神锻炼。 p>

PS: it's not a mental exercise only.

推荐答案

你的列表中的每个元素都填充了 []
如果你然后 numbers [0] .add(0); numbers [0] code> numbers [1] 显示添加的 0 ,因为它们引用相同的列表实例。

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.

将列表初始化更改为

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

显示您的预期行为。

这篇关于Dart:列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆