java add item to arraylist code example

Example 1: insert element into arraylist java

ArrayList<String> 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 2: how to add to an arraylist java

import java.util.ArrayList;
public class Details {
    public static void main(String[] args) {

        //ArrayList<String> Declaration
        ArrayList<String> al= new ArrayList<String>();
        //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 3: java arraylist add

//create ArrayList
ArrayList<String> arrayList = new ArrayList<String>();
//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 4: 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<Integer> list = new ArrayList<Integer>();
   	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, "
  }
  
}

Tags: