Java HashSet remove() 方法
remove() 是Java HashSet类的方法,用于HashSet中删除指定的元素。
1 语法
public boolean remove(Object o)
2 参数
需要删除的对象。
3 返回值
删除的对象存在返回true,否则返回false。
4 HashSet remove()示例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java HashSet.remove()方法的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
HashSet<String> set=new HashSet<String>();
set.add("Eric");
set.add("Jack");
set.add("Mark");
set.add("Lucy");
//打印HashSet
System.out.println("HashSet: " + set);
//删除元素
set.remove("Jack");
//删除元素后的HashSet
System.out.println("HashSet after removing elements: " + set);
}
}
输出结果为:
HashSet: [Eric, Mark, Lucy, Jack]
HashSet after removing elements: [Eric, Mark, Lucy]
5 HashSet remove()示例2
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java HashSet.remove()方法的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
HashSet<Integer> hashSetObject = new HashSet <>();
hashSetObject.add(45);
hashSetObject.add(67);
hashSetObject.add(98);
hashSetObject.add(24);
//打印HashSet
System.out.println("HashSet: " + hashSetObject);
//删除元素
hashSetObject.remove(98);
hashSetObject.remove(24);
//打印HashSet
System.out.println("HashSet after removing elements: " + hashSetObject);
}
}
输出结果为:
HashSet: [98, 67, 24, 45]
HashSet after removing elements: [67, 45]
6 HashSet remove()示例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java HashSet.remove()方法的例子
*/
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 Demo {
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>();
//创建Book
Book b1=new Book(101,"Thinking in Java","张三","出版社1",8);
Book b2=new Book(102,"深入理解Java虚拟机","李四","出版社2",4);
Book b3=new Book(103,"Head First 设计模式","王五","出版社3",6);
//添加Book
set.add(b1);
set.add(b2);
set.add(b3);
//遍历HashSet
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);
}
}
}
输出结果为:
102 深入理解Java虚拟机 李四 出版社2 4
101 Thinking in Java 张三 出版社1 8
103 Head First 设计模式 王五 出版社3 6
Books after remove method:
101 Thinking in Java 张三 出版社1 8
103 Head First 设计模式 王五 出版社3 6
热门文章
优秀文章