Java – Remove Element in ArrayList

 

Element in ArrayList can be removed by remove() method. In remove method, we can pass object or index number to remove.

Example of removing element in Arraylist

import java.util.ArrayList;

public class RemoveArrayListElement {

    public static void main(String[] args) {

        ArrayList<String> arlist=new ArrayList<String>();

        //<E> it is return type of ArrayList

        arlist.add("First Element"); // adding element in ArrayList
        arlist.add("Second Element");
        arlist.add("Third Element");
        arlist.add("forth Element");
        arlist.add("fifth Element");

        // remove array list element by index number
        arlist.remove(3);

        // remove ArrayList element by Object value
        arlist.remove("fifth Element");


        // get elements of ArrayList 
        for(int i=0;i<arlist.size();i++)
        {
            System.out.println("ArrayList Element "+i+" :"+arlist.get(i));
        }
    }
}

Output

Remove ArrayList Element 0 :First Element
Remove ArrayList Element 1 :Second Element
Remove ArrayList Element 2 :Third Element

Tags:

 

2 Responses to “Java – Remove Element in ArrayList”

  1. rookie says:

    Thank you very much, almost completely slipped my mind to use something like this, and it helped a lot.

  2. angie says:

    the codes were good enough for the students to comprehend more about programming,
    but does removing element in array list and removing data is the same?