【笔记】Java的HashSet

前言

Java的HashSet学习笔记

继承结构

graph TD
  Object --> AbstractCollection
  AbstractCollection --> AbstractSet
  AbstractSet --> HashSet

  Iterable --> Collection
  Collection --> Set
  Set --> HashSet


  style Object fill:#f0f8ff,stroke:#696969
  style AbstractCollection fill:#f0f8ff,stroke:#696969
  style AbstractSet fill:#f0f8ff,stroke:#696969
  style HashSet fill:#f0f8ff,stroke:#696969

  style Iterable fill:#f0f8ff,stroke:#4169e1
  style Collection fill:#f0f8ff,stroke:#4169e1
  style Set fill:#f0f8ff,stroke:#4169e1

创建对象

1
HashSet<Object> set = new HashSet<String>();

Set的相关方法

添加元素

1
set.add(<value>);

删除元素

删除指定元素

1
set.remove(<value>);

删除所有元素

1
set.clear();

获取长度

1
int length = set.size();

集合判断

判断集合是否为空

1
boolean result = set.isEmpty();

判断是否包含元素

判断是否包含指定元素
1
boolean exist = set.contains(<value>);
判断是否包含所有元素
1
2
3
Collection c = new ArrayList();

boolean exist = set.containsAll(c);

集合运算

求并集

1
2
3
Collection c = new ArrayList();

boolean success = set.addAll(c);

求差集

  • 在当前集合中删除在指定集合中存在的所有元素
1
2
3
Collection c = new ArrayList();

boolean success = set.removeAll(c);

求交集

  • 仅保留在当前集合和指定集合同时存在的所有元素
1
2
3
Collection c = new ArrayList();

boolean success = set.retainAll(c);

集合遍历

通过迭代器遍历集合

1
2
3
4
5
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Object item = iterator.next();
System.out.println(item);
}

通过for…each语法遍历

  • for…each语法实质上是迭代器的语法糖
1
2
3
for (Object item : list) {
...
}

通过forEach方法遍历

1
2
3
set.forEach((item) -> {
...
});

完成