remove method in arraylist code example

Example 1: remove item from arraylist in java

//Create the ArrayList
List<Integer> al = new ArrayList<>(); 
//Add the items
al.add(10);
al.add(18);
//Remove item(1 = 2and item in list)
al.remove(1);

Example 2: java arraylist remove

//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 3: ArrayList remove(int index) method in java

import java.util.ArrayList;
public class ArrayListRemoveIndexMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>(5);
      al.add(56);
      al.add(29);
      al.add(76);
      al.add(94);
      System.out.println("ArrayList size: " + al.size());
      for(Integer number : al)
      {
         System.out.println("Number: " + number);
      }
      // removing element at third position
      al.remove(2);
      System.out.println("ArrayList size after using remove(int index) method: " + al.size());
      // printing all elements in list
      for(Integer number : al)
      {
         System.out.println("Number: " + number);
      }
   }
}

Example 4: how to remove an element from an arraylist java

// Java program to demonstrate working of remove 
// on an integer arraylist 
import java.util.List; 
import java.util.ArrayList; 
  
public class GFG 
{ 
    public static void main(String[] args) 
    { 
        List<Integer> al = new ArrayList<>(); 
        al.add(10); 
        al.add(30); 
        al.add(1); 
        al.add(2); 
  
        // This makes a call to remove(int) and  
        // removes element 20. 
        al.remove(1); 
          
        // Now element 30 is moved one position back 
        // So element 30 is removed this time 
        al.remove(1); 
  
        System.out.println("Modified ArrayList : " + al); 
    } 
}

Tags:

Misc Example