📅  最后修改于: 2023-12-03 14:42:12.990000             🧑  作者: Mango
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.
public E remove(int index)
public boolean remove(Object o)
index
- the index of element to be removed from ArrayList.o
- the object to be removed from ArrayList.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.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
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
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.