Dart-如何初始化锯齿状数组? [英] Dart - How to initialize a jagged array?

查看:75
本文介绍了Dart-如何初始化锯齿状数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试初始化一个交错的零数组.我以为 List :: filled 是要走的路,但是我错了.

I'm trying to initialize a jagged array of zeroes. I thought List::filled is the way to go, but I was wrong.

void main() {
  List<List<int>> matrix = new List.filled(4, new List<int>.filled(4, 0));
  print('before: $matrix');
  matrix[2][3] = 1; // change a single cell
  print('after: $matrix');
}

输出不正确.尽管使用了 new 关键字,但Dart还是重用了子列表:

Output is not correct. Despite of the new keyword, Dart reused sublists:

之前:[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
之后:[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]

before: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
after: [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0,1], [0, 0, 0, 1]]

初始化锯齿数组的正确方法是什么,以使每个子数组不仅仅是指向同一列表的指针?

What's the correct way to initialize a jagged array, so that each sub array are not merely pointers to the same list?

推荐答案

如果每个索引应具有唯一值,请使用 List.generate 而不是 List.filled :

Use List.generate instead of List.filled if each index should have unique value:

var matrix = List.generate(4, (_) => List.filled(4, 0));

这篇关于Dart-如何初始化锯齿状数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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