Java HashSet remove()
remove()是Java HashSet类的一种方法,该方法将从指定的元素集中删除指定的元素
语法
以下是
remove()方法的声明:
public boolean remove(Object o)
参数
参数 |
说明 |
必需/可选 |
o |
这是将被删除到该集合中的对象(如果存在的话)。 |
必需 |
返回
如果集合中包含指定的元素,则
remove()方法将返回
true 。
异常
NA
兼容版本
Java 1.2及更高版本
示例1
import java.util.*;
public class HashSetRemoveExample1 {
public static void main(String[] args) {
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Aman");
set.add("Ajay");
System.out.println("HashSet: " + set);
set.remove("Vijay");
System.out.println("HashSet after removing elements: " + set);
}
}
输出:
HashSet: [Vijay, Ravi, Aman, Ajay]
HashSet after removing elements: [Ravi, Aman, Ajay]
示例2
import java.util.*;
public class HashSetRemoveExample2 {
public static void main(String[] args) {
HashSet<Integer> hashSetObject = new HashSet <>();
hashSetObject.add(45);
hashSetObject.add(67);
hashSetObject.add(98);
hashSetObject.add(24);
System.out.println("HashSet: " + hashSetObject);
hashSetObject.remove(98);
hashSetObject.remove(24);
System.out.println("HashSet after removing elements: " + hashSetObject);
}
}
输出:
HashSet: [98, 67, 24, 45]
HashSet after removing elements: [67, 45]
示例3
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class HashSetRemoveExample3 {
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>();
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
set.add(b1);
set.add(b2);
set.add(b3);
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
set.remove(b2);
System.out.println("Books after remove method:");
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
输出:
103 Operating System Galvin Wiley 6
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications &
Networking Forouzan Mc Graw Hill 4
Books after remove method:
103 Operating System Galvin Wiley 6
101 Let us C Yashwant Kanetkar BPB 8