java集合使用还是很广泛的,而且面试的时候也会经常问到,是否有序,是否线程安全以及底层实现的原理等等,这两天看一下jdk的底层,还是对自己更进一步了解集合实现由很大的好处。
由于代码较多,主要查看一下实例化方法,添加元素方法,移除元素方法,以及存储方式来对比各种集合的实现的区别以及联系。
1. ArrayList
ArrayList就是Object数组
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
实例化方法
初始化的时候会创建一个初始化长度为10的数组。曾经面试时被问到过这个点
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
添加元素方法
入参为泛型E,添加指定的元素到数组的末尾,返回值是TRUE,直接放到数组中存储,所以ArrayList是有序的。
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
移除元素方法
如果是int类型,删除的是索引对应的数据,如果是直接删除obj,则会只删除一个匹配的obj,不会删除所有的。
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
存储方式
从源码可以看到ArrayList是通过Object[]数组来存储数据的
2. LinkedList
实例化方法
LinkedList的实例化没有什么特殊的地方。就是直接的实例化,但是其内部的存储是有一个size记录数组的长度,需要记录其最前的一个元素和最后的一个元素。其内部定义了一个类Node,记录的当前元素,前一个元素和后一个元素。
添加元素方法
默认的添加方法是添加到末尾,也可以在某个元素之前之后添加,都是通过修改前后指针来完成的
移除元素方法
移除方法也是通过修改前后指针实现的,如果有重复的,也是只删除第一个符合条件的元素
存储方式
LinkedList是使用链表存储数据的,分配的内存空间不必是连续的,删除,添加元素的速度很快,只需要修改前后指针,但是遍历元素较慢,需要从第一个元素开始遍历
3. Vector
实例化方法
直接初始化的话,默认长度也是10,与ArrayList一样,也是通过Object[]数组存储的。
添加元素方法
方法与ArrayList类似,但是其有同步关键字,是线程安全的。
移除元素方法
重点还是线程安全的
存储方式
通过Object[]数组实现的存储
4. HashMap
实例化方法
其默认长度是16,
添加元素方法
key是不能重复的,存储是根据key的hash存放,所以是无序的
移除元素方法
通过key移除元素
存储方式
存储是通过一个Node[]数组存储的。Node是其内部的一个类,定义了一个hash,key还有value,以及记录下一个元素。HashMap的数据结构是table[Entry],entry是一个链表结构,数据的每一个元素是一个链表,不同的key但是有hashCode会落在table[hashCode]的链表上,当使用Iterator遍历时,使用的是table[entry]链表的顺序,而不是插入顺序。
####5. HashTable
实例化方法
实例化方法与HashMap类似,但是默认长度是11
添加元素方法
添加方法与hashMap类似,只是命名不一样。其实Entry,其方法是线程安全的
移除元素方法
移除之后所有的,元素会重新排列
存储方式
也是通过链表存储的。但是是线程安全的一个类
####6. LinkedHashMap
LinkedHashMap继承了HashMap,但是内部维持了一个双向链表,可以保持顺序,其Entry继承HashMap 的Node,多出了前后Entry前后元素的存储,保证其顺序性,相比HashMap,其保持了顺序,者应该是最大的优点,其他方法大多都是调用其父类的
####7. TreeMap
TreeMap是一个有序的key-value集合,他是通过红黑二叉树实现的,它的存储也是基于二叉树存储的,非线程安全,其内部的Entry是K,V,left,right,parent,和color组成,添加修改元素主要通过左旋右旋实现
8. HashSet
内部通过HashMap实现,由于HashMap的put方法添加k-y时,当新元素放入HashMap的Entry中,key与集合中原有的Entry的key相同(hashCode返回相等且equals返回true)新添加的Entry的value将会覆盖原来的Entry的value。但是key不会有任何的改变,因此如果向HashSet添加一个已经存在的元素时,新添加的元素则不会放入HashMap中,原来的元素不会有任何改变,这也就满足了set中元素不重复的特性,所有的元素value都是默认的一个new Object().
9. TreeSet
同HashSet类似,TreeSet是通过TreeMap实现的,排列无序,不可重复。
10. LinkedHashSet
LinkedHashSet继承了HashSet,根本还是HashMap实现的,使用链表式存储。