Java程序 从一个集合中删除一个特定元素
remove() method 是用来从一个集合中移除元素。它删除这个列表中指定位置上的元素。将任何后续的元素向左移动,从它们的索引中减去1。更简单地说,remove()方法是用来从一个列表中移除特定索引的元素,通过移除值并返回相同的值。
步骤: 在这个方法之上有两个标准方法,定义如下。
1.remove(int index)
2. remove(Object obj)
方法 1: Java中List接口的方法用于从List容器中移除一个指定索引的元素,并返回移除后的元素。它还将被移除的元素在List中向左移动1个位置。
语法 :
remove(int index)
参数: 它需要一个int类型的参数作为遍历的over-index,其中index值是要从列表中删除的值。
返回 Type: 一个ArrayList,其中的一些元素已经被删除。
异常: 由于要处理指定大小的索引,所以在两种情况下肯定会抛出ArrayOutOfBounds
- 任何一个提到的指数都是负面的
- 提到的索引超出(大于)ArrayList的索引。
示例:
// Java Program to Remove a Specific
// Element from a Collection
// Importing Java libraries
import java.util.List;
import java.util.ArrayList;
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an ArrayList
List<Integer> al = new ArrayList<>();
// Inserting % elements to it
al.add(10);
al.add(20);
al.add(30);
al.add(1);
al.add(2);
// If elements set is larger use
// iteration in loops to insert element
// Display ArrayList after insertion
System.out.println("Original ArrayList : " + al);
// Making 1st remove call
// which throw 20 out of list
al.remove(1);
// Here ArrayList: 10 30 1 2
// Making 2nd remove call
// which throw 30 out of list
al.remove(1);
// Here ArrayList: 10 1 2
// Printing modified Arraylist after deleting few
// elements
System.out.println("Modified ArrayList : " + al);
}
}
输出
Original ArrayList : [10, 20, 30, 1, 2]
Modified ArrayList : [10, 1, 2]
方法 2: Java中List接口的方法被用来从List中移除第一次出现的指定元素obj,如果它存在于List中。
语法 :
boolean remove(Object obj)
参数 :它接受一个List类型的参数obj,代表要从给定列表中移除的元素。
返回值 :它在从List中移除第一次出现的指定元素后返回一个布尔值True,否则如果该元素不存在于List中,该方法将返回False。
示例:
// Java program to demonstrate working of remove()
// method on an integer arraylist
// Importing specific libraries
import java.util.List;
import java.util.ArrayList;
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an ArrayList and
// storing elements in list
List<Integer> al = new ArrayList<>();
// Addition of elements to List
al.add(10);
al.add(20);
al.add(30);
al.add(1);
al.add(2);
// This makes a call to remove(Object) and
// removes element 1
al.remove(new Integer(1));
// This makes a call to remove(Object) and
// removes element 2
al.remove(new Integer(2));
// Printing modified ArrayList
System.out.println("Modified ArrayList : " + al);
}
}
输出:
Modified ArrayList : [10, 20, 30]
注意:有时它确实会抛出一个使用已废弃的函数调用或对象的警告。人们可以重新编译,以找出它发生的地方。一般来说,使用废弃的库是一个坏主意,因为这些库可能在下一个版本中消失。