Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

the difference using … operator to add list to another list

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];

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

List newData = data this will create a new object to the same reference
lets 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading