add element at index arraylist code example
Example 1: java insert into arraylist
ArrayList str=new ArrayList();
str.add(0);
str.add(1);
// Result = [0, 1]
str.add(1, 11);
// Result = [0, 11, 1]
Example 2: arraylist insert at position
//Insert a value by using arrayName.add(index, value)
//Will not remove current element at index. Will simply move all elements to
//the right.
import java.util.ArrayList;
public class main{
public static void main(String[] args){
ArrayList list = new ArrayList();
list.add(0);
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(0, 100);
//enhanced for loop will print all elements of the ArrayList
for(int element : list){
System.out.print(list + ", ");
}
//Expected output: "100, 0, 1, 2, 3, 4, 5, "
}
}
Example 3: arraylist adding at index
public void add(int index, E element)
// adding element 25 at third position
arrlist.add(2,25);
Example 4: arraylist add at index
arrlist.add(2,25);
Example 5: append to arraylist by index java
arrlist.add(2,25);
// .add(index, content)