Java如何删除集合中指定元素
实现思路:
集合中删除元素可使用collection.remove() 方法
例:
import java.util.*;
public class testClass{
public static void main(String [] args) {
System.out.println( "创建集合\n" );
int size;
HashSet collection = new HashSet ();
String str1 = "java265.com-1", str2 = "java265-2", str3 =
"java265-3", str4 = "java265-4";
Iterator iterator;
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("输出集合数据: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
collection.remove(str2);
System.out.println("删除之后 [" + str2 + "]\n");
System.out.print("删除后的集合数据: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = collection.size();
System.out.println("新集合大小: " + size + "\n");
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。