function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
pelika Gupta 2pelika Gupta 2 

Size of list increasing on adding elements to it

I have defined a list and gave it size of 6. On adding two elements in it by using list.add() method, the size of list is increasing. Why the size of list is increasing? Shouldnt it remain same?
Kindly find the snapshot of the coding.User-added image
Best Answer chosen by pelika Gupta 2
vijayabakarareddy yarrabothulavijayabakarareddy yarrabothula
use set()  method instead of add()
set(Insex,element)
 
li2.set(0,0);
li2.set(1,1);


 

All Answers

pelika Gupta 2pelika Gupta 2
i was expecting an output : (0,1,null,null,null,null)
vijayabakarareddy yarrabothulavijayabakarareddy yarrabothula
use set()  method instead of add()
set(Insex,element)
 
li2.set(0,0);
li2.set(1,1);


 
This was selected as the best answer
dsksatishdsksatish
The method add() as its names implies 'adds' the elements into the list and does not replace the elements at the specified indexes. So the elements already existing are simply pushed (to the right in this case) to make room for the new elements.

As vijayabakarareddy suggested, use the set() method, instead of the add() method, which makes an in-place change and replaces the existing values.
 
li2.set(0,0);
li2.set(1,1);



Thanks,
Satish Kumar
pelika Gupta 2pelika Gupta 2
Thank You vijayabakarareddy and dsksatish. Got the answer.