集合:
集合的作用:存储数据的
数组:
空间连续,通过下标来访问,
链表,存储空间不连续 LinkedLis
1,
支持遍历查找
针对增删除 找到对应节点的改变链表的头尾指向即可
二叉搜索树 (treeMap)
空间不连续 ,
支持二分查找
数的平衡考量
顺序排列
集合两大派系
ArrayList
该类也是实现了List的接口,实现了可变大小的数组,随机访问和遍历元素时,提供更好的性能。该类也是非同步的,在多线程的情况下不要使用。ArrayList 增长当前长度的1.5倍,插入删除效率低。
FailFast
是java集合类对并发访问 在最集合进行迭代过程中内部对象结构发生一种防护的措施,在错误检查的机制为这种有可能发生错误通过抛出异常,
上源码
public void add(E e) {
**checkForComodification();**
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
他有个版本控制,modCount 来控制他每一次的添加add()
LinkedList
-
他底层采用双向链表的数据结构实现
- 内存无需连续的空间保证
- 元素查找只能是顺序的遍历查找
-
针对删除操作性能更好一点
transient Node<E> first; //链表头部 transient Node<E> last;//链表尾部
在他进行查找的时候
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
通过源码看到他先通过一个队size的二分之后 比较他的长度,大于index 就从头开始递归查找 反之亦然,
添加数据时
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
/**
* Links e as last element.
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
第一次做add操作 先拿到最后一个节点last ,
这个可以看做时链表的指向一个新添加进来的数据
中间添加数据
/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
前一个pred指向一个新的数据的下一个next
新的数据next 指向断开数据前面的一个pred
Vector
: Collections synchronized
是线程安全的 他的底层也是一个数组,只不过他的方法都是被synchronized 修饰过得 他们线程是安全的
对于他来说我们可以借助工具类 Collections 的静态方法 通过静态方法来实现对线程的安全