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?
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.
Yes, you can use the add() method of ArrayList to insert an element at any particular index.
Assuming the name of your ArrayList is list, you can add 4 at index 1 in this manner-
list.add(1, 4);
The first parameter takes the index and the second parameter takes the value of the element you want to insert.