Java 集合
集合框架
Collection
List
ArrayList
按照插入顺序排序, 可重复
底层使用数组
可以随机进行读取、增删慢 (要挪元素在数组中的位置)
线程不安全
ConcurrentModificationException分析
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
/**
* example 1
* 在这个情况下不会抛错
*/
int length = list.size();
for (int i = 0; i < length; i++) {
if (list.get(i).equals(2)) {
list.add(10);
}
}
/**
* example 2
* 在这种情况下会抛错
*/
for(int temp : list) {
if(temp == 2) {
list.add(10);
}
}
/**
* exmple 3
* 在这种情况下会抛错
*/
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
if(iterator.next().equals(2)) {
list.add(10);
}
}
/**
* example 4
* 在这种情况下不会抛错
*/
ListIterator<Integer> listIterator = list.listIterator();
while (listIterator.hasNext()) {
if (listIterator.next().equals(2)) {
listIterator.add(10);
}
}会抛出错误的原因
在ArrayList 内有个内部类Itr
1
2
3
4
5
6private class Itr implements Iterator<E> {
/**
* 预期修改(modification)次数
*/
int expectedModCount = modCount;
}在迭代器调用next 方法的时候会检查当前类的修改次数和迭代器内的修改次数是不是一致, 如果是不一致的话 就爆炸.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch(IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public E add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
exceptedModCount = modCount;
} catch (IndexOutOfBoundException ex) {
throw new ConcurrentModificationException();
}
}在案例1 中没有使用到迭代器相关的api
在案例 2, 3 中使用了迭代器相关的api 在外部类的mod time 发生了改变的时候没有对迭代器内部的mod time 同时进行修正, 当再次调用next 的时候发现内部类记录的修改次数和类外部的修改次数不一样.爆炸.
Vector
- 按照插入顺序排序 可重复
- 底层使用数组
- 可以随机读取 增删慢(要挪元素在数组中的位置)
- 线程安全
LinkedList
- 按照插入顺序排序 元素可重复
- 通过链表的方式保存数据
- 不可以随机读取数据 要通过头节点 或者尾节点 以遍历的方式获得所得的元素 但是 add 和remove的方法快
Set
HashSet
排列无序 不可重复 底层是HashMap.
TreeSet
内部是TreeMap的sortedSet
LinkedHashSet
内部是LinkedHashMap
Queued
- PriorityQueued
Map
HashMap
key不可重复 value 可以重复
底层hash表
线程不安全 (可能会造成endless loop)
允许key值为null
HashTable
key不可重复
底层hashtable
线程安全
key value 都不允许为null
TreeMap
key不可以重复