前言
Java的集合(java.util.Collection)学习笔记
集合,用于存储一组元素。提供了维护集合的相关操作。
元素是否重复是依靠元素自身equals方法比较的结果而定的。
继承结构
graph TD
Collection[Collection] --> List[List]
Collection --> Set[Set]
Collection --> Map[Map]
List --> E[ArrayList]
List --> F[LinkedList]
Set --> G[HashSet]
Map --> H[HashMap]
Queue --> I[LinkedList]
创建对象
1
| Collection c = new ArrayList();
|
使用泛型创建对象
1
| Collection<T> c = new ArrayList<T>();
|
1
| Collection<T> c = new ArrayList<>();
|
实例方法
添加元素
<value>:元素
1
| boolean success = c.add(<value>);
|
删除元素
1
| boolean success = c.remove(<value>);
|
获取集合长度
判断集合是否为空
1
| boolean isEmpty = c.isEmpty();
|
清空集合元素
判断元素是否存在
1
| boolean exist = c.contains(<value>);
|
取并集
1 2 3 4
| Collection c1 = new ArrayList(); Collection c2 = new ArrayList();
boolean success = c1.addAll(c2);
|
判断当前集合是否包含给定集合
1
| boolean success = c1.containsAll(a2);
|
从c1中删除两集合共有元素
1
| boolean success = c1.removeAll(c2);
|
遍历集合
通过迭代器遍历集合
1 2 3 4 5
| Iterator it = c.iterator();
while (it.hasNext()) { Object obj = it.next(); }
|
for…each遍历集合
1 2 3
| for (Object obj : c) { ... }
|
List的额外方法
将元素插入指定位置
<index>:想要操作元素的下标
1 2
| List list = new ArrayList(); list.add(<index>, <value>);
|
删除指定位置元素
取子集
<index_first>:取子集的开始下标
<index_last>:取子集的结尾下标
1
| list.subList(<index_first>, <index_last>);
|
删除集合中给定区间的元素
1
| list.subList(<index_first>, <index_last>).clear();
|
集合与数组的转换
集合转换为数组
1
| Object[] array = c.toArray();
|
数组转换为集合
1 2 3
| Object[] array = {};
Collection c = Arrays.asList(array);
|
排序
- 集合工具类Collections的静态方法sort仅能对List集合进行排序
1 2 3
| List list = new ArrayList();
Collections.sort(list);
|
自定义排序规则
- 实现Comparable接口,重写
compareTo()方法
- 当返回时<0时,当前对象小于传入对象
- 当返回值>0时,当前对象大于传入对象
- 当返回时=0时,当前对象等于传入对象
1 2 3
| public int compareTo() { ... }
|
LinkedList的额外方法
添加首尾元素
<value>:对应数据类型的元素
删除首尾元素
修改指定下标的元素
<index>:下标值
1
| list.setFirst(<index>, <value>);
|
获取首尾元素
Map的额外方法
添加键值对
1
| map.put(<key>, <value>);
|
根据键删除键值对
根据键获取值
只有键不存在时才添加值
1
| map.putIfAbsent(<key>, <value>);
|
获取简直对
获取所有键值对
1 2 3
| Map.Entry entry = map.entrySet(); entry.getKey(); entry.getValue();
|
获取所有key
1
| Set keys = map.keySet();
|
获取所有value
1
| Collection values = map.values();
|
判断是否存在指定键
1
| boolean exist = map.containsKey(<key>);
|
判断是否存在指定值
1
| boolean exist = map.containsValue(<value>);
|
工具类
批量加入数据
<elements>:任意数量的数据,多个数据间用逗号隔开
1
| Collections.addAll(list, <elements>);
|
获取集合中的最大值
获取集合中的最小值
位置反转
1
| Collections.revers(list);
|
正序排序
交换
<index_1>、<index_2>:两个元素的下标
1
| Collections.swap(list, <index_1>, <index_2>);
|
完成