I was using MutableList .add(index, elemet) , it not worked as i expected.
It’s not saving element with by defined index it just save them by first cum fist save with index.
Example: i made list add : index 0 element a, index 3 element b, index 4 element c, index 2 element d.
And when i check the result it will not save them the index i mentioned.
May be i have not understood mutablelist.add(index, element).
Please help me to understand it better.
list.add(index, element)
will add the element to the list so that it will have the index specified. To do so it will the element at this position to the right as well as all subsequent elements.
l = [0, 1, 2, 3, 4]
l.add(index = 2, element=5)
l = [0, 1, 5, 2, 3, 4]
l.add(index = 1, element=6)
l = [0, 6, 1, 5, 2, 3, 4]
Also it should not be possible to add an element at an index that is not valid (index < 0 || index > size
).
The index of an element in a list is not supposed to stay the same when you start to insert elements. When you insert an element a list will keep the order or elements relative to each other and insert the new element at the specified position. That means that if you insert multiple elements in a row it might change the index of previous elements.
To work around that you can either insert the element with the lowest index first or probably a better solution you should look into using maps if the index is relevant and is not determined by the order the elements are added.
Thanks, I understand what was going wrong.