arraylist .remove java code example

Example 1: How to remove element from arraylist in java

// Java.util.ArrayList.remove(Object) method example
import java.util.ArrayList;
import java.util.List;
public class ArrayListRemoveObjectMethod
{
   public static void main(String[] args)
   {
      List<Integer> al = new ArrayList<>();
      al.add(56);
      al.add(28);
      al.add(39);
      al.add(59);
      al.add(82);
      System.out.println("Before using ArrayList.remove(Object) method size of ArrayList: " + al);
      // removes element 56
      al.remove(new Integer(56));
      // removes element 28
      al.remove(new Integer(28));
      System.out.println("After using ArrayList.remove(Object) method size of ArrayList: " + al);
   }
}

Example 2: 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 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);
      }
   }
}

Tags:

Java Example