Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Add an element between two elements in arraylist

i want to add an element between two other elements in an arraylist like:

Element 1
Element 2
Element 3

Adding an element:

Element 1
Element 4 <---- Adding element 4 between 1 and 2.
Element 2
Element 3

Is this possible?

like image 621
Amirhossein Avatar asked Dec 17 '22 13:12

Amirhossein


1 Answers

Yes - you want the overload of add that takes an index. In this case, the index would be 1:

list.add(1, 4); // Index then value

Note that adding an element involves copying all existing elements after that (so values 2 and 3 in your example), so if you do this a lot with a very large list, it can have performance implications.

like image 170
Jon Skeet Avatar answered Dec 31 '22 14:12

Jon Skeet