📜  java arraylist remove - Java (1)

📅  最后修改于: 2023-12-03 14:42:12.990000             🧑  作者: Mango

Java ArrayList Remove

Java ArrayList is a dynamic array that can grow or shrink according to the number of elements. remove method of ArrayList removes the object at specified index or the first occurrence of specified object from ArrayList. In this article, we will discuss about remove method of ArrayList.

Syntax
public E remove(int index)
public boolean remove(Object o)
Parameters
  • index - the index of element to be removed from ArrayList.
  • o - the object to be removed from ArrayList.
Return Value
  • remove(int index) - returns the object that has been removed from ArrayList.
  • remove(Object o) - returns true if the specified object is found and removed, false otherwise.
Examples
Removing element at specified index
import java.util.ArrayList;

public class Example {
   public static void main(String[] args) {
      ArrayList<String> fruits = new ArrayList<>();
  
      fruits.add("Apple");
      fruits.add("Orange");
      fruits.add("Banana");

      System.out.println("Before removal: " + fruits);

      String removedFruit = fruits.remove(1);

      System.out.println("After removal: " + fruits);
      System.out.println("Removed fruit: " + removedFruit);
   }
}

Output:

Before removal: [Apple, Orange, Banana]
After removal: [Apple, Banana]
Removed fruit: Orange
Removing first occurrence of specified object
import java.util.ArrayList;

public class Example {
   public static void main(String[] args) {
      ArrayList<String> fruits = new ArrayList<>();
  
      fruits.add("Apple");
      fruits.add("Orange");
      fruits.add("Banana");

      System.out.println("Before removal: " + fruits);

      boolean removedFruit = fruits.remove("Orange");

      System.out.println("After removal: " + fruits);
      System.out.println("Removed fruit: " + removedFruit);
   }
}

Output:

Before removal: [Apple, Orange, Banana]
After removal: [Apple, Banana]
Removed fruit: true
Conclusion

We have learned how to remove elements from Java ArrayList using remove method. We can remove elements either by specifying the index or the object to be removed.