Is there a way to initialize a list outside the loop, have it deleted and reuse in dart?

I have here 2 functions,

List<List<int>> inputmatrix() {
  print("Please insert the number of rows of this matrix?"); int k = int.parse(stdin.readLineSync());
  print("Please insert the number of column of this matrix?"); int q = int.parse(stdin.readLineSync());
  List<List<int>> d = [];
  for (var i = 0; i < k; i++) {
    List<int> d1 = [];
    for (var j = 0; j < q; j++) {
      print("Please insert element [${i + 1},${j + 1}]");
      int a = int.parse(stdin.readLineSync());
      d1.add(a);
    }
    d.add(d1);
  }
  return d;
}

List<List<int>> inputmatrix1() {
  print("Please insert the number of rows of this matrix?"); int k = int.parse(stdin.readLineSync());
  print("Please insert the number of column of this matrix?"); int q = int.parse(stdin.readLineSync());
  List<List<int>> d = [];
  List<int> d1 = [];
  for (var i = 0; i < k; i++) {
    for (var j = 0; j < q; j++) {
      print("Please insert element [${i + 1},${j + 1}]");
      int a = int.parse(stdin.readLineSync());
      d1.add(a);
    }
    d.add(d1);
    d1.clear();
  }
  return d;
}

but inputmatrix() does work, and inputmatrix1() doesn't. When array d1 is cleared in inputmatrix1(), so does the value of that in d. And yet, when I pasted the declaration of d1 inside the loop, it works. Could anyone tell me why Dart behaves like this? Dart returns by value, but if that's the case then inputmatrix() shouldn't work either. Thank you in advance.

Upvotes: 0

Views: 85

Answers (1)

julemand101
julemand101

Reputation: 31219

When you do:

d.add(d1);

You are adding a reference to the list which d1 points at. This is fine in inputmatrix since you are creating a new list for each iteration in your first for-loop and points to this new list with d1.

But in inputmatrix1 you are reusing the same list instance and keep a reference to this list in d1. Since you are then calling .clean() on this same list instance it will be changed for all who are referring to the same list instance (like your d list of lists).

Again, d1 is just a reference to a list and when you are calling add() you are adding the value of the reference to the list. But this value should be seen as a pointer to a list instance and not the list itself.

About the question I don't know what issue you are trying to solve since inputmatrix seems like the correct way to do what you are trying to achieve. There is nothing wrong declaring variables in a more restricted scope.

Upvotes: 1

Related Questions