Java ArrayList.remove() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn about ArrayList.remove() method. ArrayList provides two overloaded remove() methods. 1] remove element by index position and 2] remove element by Object.

ArrayList.remove(int index) syntax

Removes the element at the specified index position from the list. Shifts remaining elements to the left.

E java.util.ArrayList.remove(int index)

Parameter

index - index of the element to be removed

Return

E the element that was removed from the list.

Exception

throws IndexOutOfBoundsException exception if you try to remove element out of range.

ArrayList.remove(Object o) syntax

Removes the first occurrence of the specified element from this list.

boolean java.util.ArrayList.remove(Object o)

Parameter

o - Element to be removed from this list, if present.

Return

true If this list contained the specified element.

Java ArrayList.remove() example

Refer below steps

  • Constructs an empty ArrayList with an initial capacity using new ArrayList<String>().
  • Add some elements in colors ArrayList using add() method.
  • Remove element by index position (colors.remove(index)), Here we have removed 1st index position element. It return the element which was removed from the list.
  • Remove element by Object (colors.remove(element)), It removes the first occurrence of the specified element from this list, returns boolean value.
  • Print remaining elements.
package com.technicalkeeda.app;

import java.util.ArrayList;

public class ArrayListRemove {
    public static void main(String[] args) {

        ArrayList <String> colors = new ArrayList <String> ();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        colors.add("Pink");
        colors.add("Black");
        colors.add("White");

        int index = 1;
        System.out.println("Remove by index :- " + index + " Element:-" + colors.remove(index));

        String element = "Black";
        System.out.println("Remove by Object " + colors.remove(element));

        System.out.println("\nRemaining Elements:- ");
        for (String color: colors) {
            System.out.println(color);
        }
    }
}

Output

Remove by index :- 1 Element:-Green
Remove by Object true

Remaining Elements:- 
Red
Blue
Pink
White


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0325 seconds.