Simple Add () method was used for adding a element at the end of the list however there is another variant of Add method wh Ich is used for adding a element to the specified index.
public void add(int index, Object element)
This method adds the element at the given index.
Example
1:import java.util.ArrayList;
2:publicclass Addmethodexample {
3: Public Static void Main (string[] args) {
4: //ArrayList of String type
5: New Arraylist<string> ();
6: //Simple Add () methods-adding elements at the end
One : //adding element to the 4th position
: //4th position = 3 Index as index starts with 0
: System.out.println ("Elements after adding string Howdy:"+ al);
: //adding String to 1st position
: System.out.println ("Elements after adding string bye:"+ al);
Output:
Elements after adding string howdy:[hi, Hello, String, Howdy, test]elements after adding string bye:[bye, Hi, Hello, Strin G, Howdy, Test]
Java ArrayList Add (int index, E Element) example