Java list remove(int index)方法及示例
Java中List接口的remove(int index)方法用于从List容器中移除一个指定索引的元素,并在移除后返回该元素。它还可以将被删除元素之后的元素在List中向左移动1个位置。
语法:
**E remove(int index)**
Where, E is the type of element maintained
by this List collection
参数 :它接受一个整数类型的参数 index ,代表需要从列表中删除的元素的索引。
返回值 :在移除元素后,它返回给定索引处的元素。
以下程序说明了Java中List的remove(int index)方法。
程序1 :
// Program to illustrate the
// remove(int index) method
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declare an empty List of size 5
List<Integer> list = new ArrayList<Integer>(5);
// Add elements to the list
list.add(5);
list.add(10);
list.add(15);
list.add(20);
list.add(25);
// Index from which you want to remove element
int index = 2;
// Initial list
System.out.println("Initial List: " + list);
// remove element
list.remove(index);
// Final list
System.out.println("Final List: " + list);
}
}
输出。
Initial List: [5, 10, 15, 20, 25]
Final List: [5, 10, 20, 25]
示例2 :
// Program to illustrate the
// remove(int index) method
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declare an empty List of size 5
List<String> list = new ArrayList<String>(5);
// Add elements to the list
list.add("Welcome");
list.add("to");
list.add("Geeks");
list.add("for");
list.add("Geeks");
// Index from which you want
// to remove element
int index = 2;
// Initial list
System.out.println("Initial List: " + list);
// remove element
list.remove(index);
// Final list
System.out.println("Final List: " + list);
}
}
输出。
Initial List: [Welcome, to, Geeks, for, Geeks]
Final List: [Welcome, to, for, Geeks]
参考资料 : https://docs.oracle.com/javase/8/docs/api/java/util/List.html#remove-int-