Java程序从Set中删除项目
Java中的集合是根据数学集合建模的,它不能包含重复的元素。set接口包含从Collection继承的方法。该方法remove()从set集合中删除指定的项目。
一个程序演示了如何从Set中删除项目remove(),如下所示:
示例
import java.util.*;
public class Example {
public static void main(String args[]) {
int arr[] = {5, 10, 10, 20, 30, 70, 89, 10, 111, 115};
Set<Integer> set = new HashSet<Integer>();
try {
for(int i = 0; i < 10; i++) {
set.add(arr[i]);
}
System.out.println(set);
set.remove(89);
System.out.println(set);
}
catch(Exception e) {}
}
}输出结果
[115, 20, 5, 70, 89, 10, 30, 111] [115, 20, 5, 70, 10, 30, 111]
现在让我们了解上面的程序。
该add()函数用于使用for循环将元素从数组arr添加到set集合中。然后显示该集合。数组中的重复元素在集合中不可用,因为它不能包含重复元素。证明这一点的代码片段如下所示-
int arr[] = {5, 10, 10, 20, 30, 70, 89, 10, 111, 115};
Set<Integer> set = new HashSet<Integer>();
try {
for(int i = 0; i < 10; i++) {
set.add(arr[i]);
}
System.out.println(set);使用该remove()方法将元素89从集合中删除。然后再次显示该组。证明这一点的代码片段如下所示-
set.remove(89);
System.out.println(set);
}
catch(Exception e) {}