Home > Software engineering >  What is the difference of using ... operator to add list to another list?
What is the difference of using ... operator to add list to another list?

Time:06-11

I usually use this method to add list into another list

  List newData = data;

But one of my developer friend use this ... operator to add list into another list like this, what is the difference between this both method ? I try to search for the answer but cannot understand.

  List data = [
    {
      'value': 'value one',
    },
    {
      'value': 'value two',
    },
  ];

  List newData = [...data];

CodePudding user response:

List newData = data this will create a new reference to the same object. Let's assume that List data = ['a', 'b', 'c']; so if you called newData[0] = 'x';

//Lets assume the following
List data = ['a', 'b', 'c'];
List newData = data;
data[0] = 'x';
print(data);
print(newData);

//this code will print the same data for both lists, you will find in the console:
['x', 'b', 'c']
['x', 'b', 'c']
//changing the first value in the data List effected both lists

but if you created a newData = [...data]; this will create a new list and copy the data from data to newData

//Lets assume the following
List data = ['a', 'b', 'c'];
List newData = [...data];
data[0] = 'x';
print(data);
print(newData);

//this code will print the same data for both lists, you will find in the console:
['x', 'b', 'c']
['a', 'b', 'c']
//changing the first value in the data List effected only the data list

usually making a new pointer to the same reference is not what's intended but using the second method will take more space from the memory


UPDATE:

  • when to use the first method and when to use the second if you want to update your list, remove, replace or add elements without saving the old data, then you can use the first method, but personally, I don't see that you need to create a newData list because you can do what you want directly to your data list

  • If you want to update your list but saving your old data to refer to it in the future, then you must use the second method, because playing with newData list does not effect the original list in that case

  • Related