arraylist add java 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: insert element into arraylist java
ArrayList arrayList = new ArrayList<>();
// Adds element at the back of the list
arrayList.add("foo");
arrayList.add("bar");
// Result = ["foo", "bar"]
// Adds element at the specified index
arrayList.add(1, "baz");
// Result = ["foo", "baz", "bar"]
Example 3: ArrayList add(int index, E element) method in java
import java.util.ArrayList;
public class ArrayListAddMethodExample
{
public static void main(String[] args)
{
// creating an empty ArrayList with initial capacity
ArrayList al = new ArrayList(6);
al.add(12);
al.add(14);
al.add(16);
al.add(18);
al.add(20);
// adding element 15 at fourth position
al.add(3, 15);
for(Integer number : al)
{
System.out.println("Number: " + number);
}
}
}
Example 4: how to add to an arraylist java
import java.util.ArrayList;
public class Details {
public static void main(String[] args) {
//ArrayList Declaration
ArrayList al= new ArrayList();
//add method for String ArrayList
al.add("Ram");
al.add("Shyam");
al.add("CPS");
al.add("John");
al.add("Steve");
System.out.println("Elements of ArrayList of String Type: "+al);
Example 5: java arraylist add
//create ArrayList
ArrayList arrayList = new ArrayList();
//add item to ArrayList
arrayList.add("item");
//check if ArrayList contains item (returns boolean)
System.out.println(arrayList.contains("item"));
//remove item from ArrayList
arrayList.remove("item");
Example 6: arraylist adding at index
public void add(int index, E element)
// adding element 25 at third position
arrlist.add(2,25);