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.LinkedList;
public class Main { 
  public static void main(String[] args) {
    LinkedList<String> cars = new LinkedList<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 eliminates an item from the list, either by its position or its value. When removing by position, this method returns the removed item. When removing by value, it returns true if the value is found and false otherwise.

 If multiple elements in the list have the same value, only the first occurrence is deleted.

If the list contains integers and you aim to delete an integer based on its value, you need to pass an Integer object. See More Examples below for a demonstration.

Syntax

One of the following:

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

T denotes to the data type of items within the list.

Parameter Values

Parameter

Description

index

Required. The position of the item to be deleted.

item

Required. The value of the item to be deleted.

Technical Details

Returns:

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

Throws:

IndexOutOfBoundsException – If the index is less than zero, equal to the size of the list or greater than the size of the list.

More Examples

Example

Eliminate an integer from the list using both its position and its value.
import java.util.LinkedList;
public
class Main {
 public static void main(String[] args) {
    LinkedList<Integer> list = new LinkedList<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);
  }
}