4

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?

0

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Simple as that:

myList.add(1, "Element 4"); 

See this documentation for further details.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.