Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

remove()

Example

Delete elements from a list.

import java.util.ArrayList;
public class Main { 
  
public static void main(String[] args) {
    
ArrayList<String> cars = new ArrayList<String>();
    cars
.add("Volvo");
    cars
.add("BMW");
    cars
.add("Ford");
    cars
.add("Mazda");
   cars.remove(0);
    System.out.println(cars);
  }
}

Definition and Usage

The remove() method deletes an item from the list by position or value. If a position is specified, it returns the removed item. If a value is specified, it returns true if the item was found and removed, otherwise false.

If a value is specified and multiple elements in the list share the same value, only the first occurrence is deleted.

When dealing with a list of integers and you want to remove an integer by its value, you must pass an Integer object. Refer to the examples below for more details.

Syntax

One of the following options:

public T remove(int index)
public boolean remove(Object item)

T denotes the data type of the elements in the list.

Parameter Values

Parameter

Description

index

Required: The index of the item to be deleted.

item

Required: The value of the item to be deleted.

Technical Details

Returns:

If an object is passed as an argument, it returns true if the object is found in the list and false otherwise. If an index is passed, it returns the object that was removed.

Throws:

IndexOutOfBoundsException occurs if the index is negative, equal to the list’s size, or exceeds the list’s size.

More Examples

Example

Delete an integer from the list either by position or by value.   

import java.util.ArrayList;
public class Main { 
  public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(5);
    list.add(8);
    list.add(9);
    list.add(1);
    list.remove(Integer.valueOf(1)); // Remove by object
    list.remove(1); // Remove by index
    System.out.println(list);
 }
}