Java集合框架
List
ArrayList/LinkedList
column | 优点 | 缺点 | 底层实现 |
---|---|---|---|
ArrayList | 随机访问元素较快 | 中间元素的插入和删除较慢 | 数组 |
LinkedList | 中间元素的插入和删除,顺序访问的优化 | 随机访问元素较慢 | 双向链表 |
- ArrayList: 每次进行插入和删除操作需要移动大量元素(除非在末尾插入),是一个O(n)操作,因而速度较慢,而随机访问元素可以直接根据索引得到;
- LinkedList: 每次随机访问元素需要依次遍历获才能得到该节点的指针(若是全部遍历的情形,使用iterator效率同样很高),因而速度较慢,而插入和删除元素时仅需前后节点变动即可。
Iterator
容器的实现有很多种,而我们想对容器进行遍历操作的话,首先不应该关心容器实现的细节,其次遍历操作应该是轻量级的。迭代器统一了对容器的访问方式,同时创建它的代价很小。值得注意的是,Iterator只能单向移动。
HashMap
要求映射中的key是不可变对象(不可变对象是指该对象在创建后它的哈希值不会被改变)。如果对象的哈希值发生变化,Map对象很可能就定位不到映射的位置了。
存储结构:
数组+链表+红黑树(jdk1.8引进)
源码中对几个字段的叙述:
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;
/**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;
threshold
length
loadfactor
其中:length指数组长度,默认是16,loadFactor是负载因子,threshold = length*loadfactor,是允许存储的最大K-V元素的个数,threshold大小的确定是对时间和空间的一种权衡,默认是0.75,建议大家不要修改,除非在时间和空间比较特殊的情况下,如果内存空间很多而又对时间效率要求很高,可以降低负载因子Load factor的值;相反,如果内存空间紧张而对时间效率要求不高,可以增加负载因子loadFactor的值,这个值可以大于1。注意loadfactor是可以大于1的。