Reputation: 18758
I have a List<String>
and I want to create a square matrix (2-dimensional array/list) of Set<String>
with the same dimensions as the length of the List<String>
.
I tried using
List.filled(entries.length, List.filled(entries.length, Set<String>()));
but the problem is that it seems that each row of my matrix refers to the same list instance, so changing a value in one row changes it in all the others as well.
So then I tried
List.filled(entries.length, List.from(List.filled(entries.length, Set<String>())));
but I still have the same problem. Eventually I surrendered and resorted to
List<List<Set<String>>> matrix = [];
for(int i=0; i<entries.length; i++) {
List<Set<String>> row = [];
for (int n = 0; n<entries.length; n++) {
row.add(Set<String>());
}
matrix.add(row);
}
It works, but it's ugly. Is there a cleaner way to do this?
Upvotes: 2
Views: 2394
Reputation: 490
Probably, you could use Matrix2 class (or matrixes with other dimensions: Matrix3, Matrix4). Unfortunately, I have no experience in using these classes, but maybe it has a sense for you. These classes have constructors for generating matrix from lists.
Upvotes: 0
Reputation: 76243
List.generate(n, (_) => List.generate(n, (_) => <String>{}));
Upvotes: 5