1 需求
需求:添加元素
public boolean add(E e)需求:删除元素
public boolean remove(Object o)需求:判断元素是否存在
public boolean contains(Object o)需求:判断 HashSet 是否为空
public boolean isEmpty()需求:获取 HashSet 的大小
public int size()需求:遍历HashSet
public Iterator
public void clear()
2 接口
3 示例
import java.util.HashSet;
import java.util.Iterator;
/**
* HashSet常见操作:
* (1)添加元素
* (2)删除元素
* (3)判断元素是否存在
* (4)判断HashSet是否为空
* (5)判断HashSet的大小
* (6)遍历HashSet
* (7)清空HashSet
*/
public class Test {
public static void main(String[] args) {
// 创建HashSet对象
HashSet
// 添加元素
hashSet.add("a");
hashSet.add("b");
hashSet.add("c");
hashSet.add("c");
hashSet.add("d");
// 删除元素
hashSet.remove("d");
// 检查元素是否存在
System.out.println(hashSet.contains("a"));
// 判断 HashSet 是否为空
System.out.println(hashSet.isEmpty());
// 获取 HashSet 的大小
System.out.println(hashSet.size());
// 遍历HashSet方法一:for-each 循环来遍历它
for (String s : hashSet) {
System.out.println(s);
}
// 遍历HashSet方法二:迭代器 循环来遍历
Iterator
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// 清空HashSet
hashSet.clear();
}
}
4 参考资料
相关阅读
发表评论