Use Java's ArrayList.remove() function to remove the element at the specified index position
In the Java collection framework, ArrayList is a dynamic array that provides many convenient methods to operate and manage elements. Among them, remove() is one of the most commonly used functions of the ArrayList class. The remove() function can remove elements from the ArrayList based on the index position.
Let’s take a look at the sample code that uses the ArrayList.remove() function to remove elements at specified index positions:
import java.util.ArrayList; public class Main { public static void main(String[] args) { // 创建一个ArrayList对象 ArrayList<String> list = new ArrayList<>(); // 向ArrayList中添加元素 list.add("apple"); list.add("banana"); list.add("cherry"); list.add("durian"); System.out.println("原始ArrayList:" + list); // 移除索引位置为2的元素 list.remove(2); System.out.println("移除索引位置为2的元素后的ArrayList:" + list); } }
Run the above code, we will get the following output:
原始ArrayList:[apple, banana, cherry, durian] 移除索引位置为2的元素后的ArrayList:[apple, banana, durian]
It can be seen from the output that after removing the element at index position 2, the element "cherry" was successfully removed from the ArrayList.
It should be noted that the index of ArrayList starts from 0. That is, the first element has index 0, the second element has index 1, and so on.
In addition, the ArrayList.remove() function has another overloaded version that can accept an element as a parameter to remove the specified element in the ArrayList. An example is as follows:
import java.util.ArrayList; public class Main { public static void main(String[] args) { // 创建一个ArrayList对象 ArrayList<String> list = new ArrayList<>(); // 向ArrayList中添加元素 list.add("apple"); list.add("banana"); list.add("cherry"); list.add("durian"); System.out.println("原始ArrayList:" + list); // 移除元素"cherry" list.remove("cherry"); System.out.println("移除元素"cherry"后的ArrayList:" + list); } }
Running the above code, we will get the following output:
原始ArrayList:[apple, banana, cherry, durian] 移除元素"cherry"后的ArrayList:[apple, banana, durian]
Similarly, the element "cherry" was successfully removed from the ArrayList.
To sum up, the ArrayList.remove() function is a very convenient method that can remove elements in ArrayList based on index position or element value. In practical applications, especially when elements need to be frequently inserted and removed, the use of the ArrayList.remove() function can greatly improve the efficiency and readability of the code. I hope this article will help you when using ArrayList to remove elements.
The above is the detailed content of Use java's ArrayList.remove() function to remove the element at the specified index position. For more information, please follow other related articles on the PHP Chinese website!