一、學習目的
由於最近在項目中發現,一個項目中用到的java中最多也是最重要的知識基本上就是集合類的使用和多線程的開發,而集合類基本都會使用像List、ArrayList或者HashMa,有些場景可能會用到HashTable或者HashSet等集合。總的來說,java中的對於集合的操作給我們編程帶來了很大的便利,但是作爲一名合格的程序員,我覺得不僅要會使用,而且應該知道實現細節。同時閱讀技術牛人寫出來的代碼對於自己的開發水平也會有很大的幫助。
二、學習目標
瞭解Vector的繼承關係以及其內部實現,能夠更加靈活的使用
三、學習筆記
在java的代碼實現中,如果你去認真觀察的話,他的繼承關係有些複雜,也可以說有些冗餘,但是到目前爲止我還不知道爲什麼會有這種冗餘出現,或者是代碼開發者不小心造成的,也有可能是代碼開發者故意這麼寫,讓我們在看代碼的時候不用那麼麻煩吧.具體的也說不清,下面看一些java中關於vector實現的類圖:
在上面的類圖中,基本上所有的集合類都會實現Collection接口,並且每一個集合類中都會實現自己的迭代器函數,用於循環遍歷,必要時候可以使用迭代器進行刪除某個迭代器指向的元素。我並沒有將所有的類方法寫到裏面,這個類圖主要是想讓讀者能夠看到清晰的繼承關係。從圖中可以看到Vector繼承了AbstractList<E>這個抽象類,但同時AbstractList又實現了List<E>接口,但Vector也實現了List<E>接口,這個地方總感覺有些多餘.如果有知道的還請指導。通過接口的繼承關係以及Vector的實現關係,可以理解爲Vector類實現了以下接口:Iterable、Collection、List、RandomAccess、Cloneable、Serializable。上述接口在以後的學習過程中還會學到,這篇文章中就不深入瞭解其細節了,只要大概知道是幹什麼的就行。
下面就是關於代碼層面的學習:
在java.util包中打開Vector.java這個類,首先類名以及繼承代碼
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
下一行protected Object[] elementData;
通過這一行代碼相信大家都明白了Vector底層是通過數組的方式進行數據存儲的,所以對於Vector的增刪改查都可以使用跟數組相似的邏輯操作進行。
下面看一下該類中主要的方法都有哪些:
1. size 方法的實現
public synchronized int size() {
return elementCount;
}
返回Vector中元素個數,這邊的元素個數與數組大小不是一個概念。vector中元素個數是通過
<pre name="code" class="java">protected int elementCount;
2. isEmpty 函數的實現
<pre name="code" class="java">public synchronized boolean isEmpty() {
return elementCount == 0;
}
判斷該Vector是否爲空,這些都比較簡單,也很容易看懂的,以後就不羅列了。3. boolean contains(Object o);//是否包含某個對象
public boolean contains(Object o) {
return indexOf(o, 0) >= 0;
}
通過indexOf來查找該元素存在哪個位置上,如果該元素不存在,則返回-1。contains方法使用了indexOf方法,後面也會遇到Index方法的。
4. index方法的實現
<pre name="code" class="java">public synchronized int indexOf(Object o, int index) {
if (o == null) {
for (int i = index ; i < elementCount ; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = index ; i < elementCount ; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
該方法表示從index個位置開始數起,如果存在於object相同的對象,那麼就返回該對象所在位置處的座標,否則返回-1;我覺得讓我考慮的話,應該會把object爲null的情況給忽略,這樣就導致了算法的不普遍性。而循環遍歷數組後通過對象的equals方法,這同時用到了java的多態性,object只是一個對象的引用而已,如果該對象的實際類型的類有重載過equals方法,那麼按照重載後的方法判斷是否相同;如果沒有重載,那麼必須兩個對象的地址相同纔會判定爲相同對象。所以,以後我們寫程序的時候如果要依據對象中的字段來判斷對象是否相同的話,則必須重載Object超父類中的equals方法纔行。
5.lastIndexOf方法的實現
<pre name="code" class="java">public synchronized int lastIndexOf(Object o, int index) {
if (index >= elementCount)
throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
if (o == null) {
for (int i = index; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = index; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
跟indexOf方法實現相同,只是從後向前遍歷,確實有時候知道某個元素在靠後的位置,使用向前遍歷能夠節約系統時間。6.elementAt,firstElement,lastElement方法
<pre name="code" class="java">public synchronized E elementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
}
return elementData(index);
}
6中的方法全部調用elementData方法,就沒必要說了,直接看elementData方法吧
7.elementData方法的實現
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
這不太合適吧?我還期待着有什麼精妙的實現呢.原來就是對數組的操作.
8.removeElementAt方法的實現
在尋找第7個方法的時候我無意間看到了一個很好的實現方法。確實感覺到了在java中無處不在的代碼重用。不廢話了,看代碼
<pre name="code" class="java">public synchronized void removeElementAt(int index) {
modCount++;
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
elementCount--;
elementData[elementCount] = null; /* to let gc do its work */
}
在system類中實現的arraycopy方法直接把這個刪除方法搞定,這個方法中的參數代表什麼意思呢?第一個參數表示源數組,第二個參數源數組的開始位置,第三個參數表示目的數組,第四個參數表示目的數組的開始位置,第五個參數表示複製多少個數據過去。認真思考後發現,這樣拷貝的話,那麼源數組中的最後一個元素並沒有替換,還是存在原來的位置,且與倒數第二個位置上的元素相同。這樣的話刪除的不完全啊。對,確實這樣操作刪除的不完全,但是後面的兩句話將arraycopy的缺點給彌補了.好巧妙。
9.clone方法的實現
<pre name="code" class="java">public synchronized Object clone() {
try {
@SuppressWarnings("unchecked")
Vector<E> v = (Vector<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, elementCount);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
clone方法一直都是很神祕的一個方法,學過c++的一定都見過深拷貝和淺拷貝這兩個名詞,但這是什麼意思呢?在java中是否也存在相同的問題呢?答案是肯定的。在java中確實存在相同的問題,這兩個名詞都只會在類中有指向某個非基本類型對象的時候纔會存在的問題,這也就存在了java中的另外兩個名詞,值傳遞和引用傳遞的概念了。不過相信能夠讀到這邊的讀者都對這些概念有一個非常深刻的瞭解。迴歸正題。如果該函數中只使用super.clone()來進行對象的拷貝的話,那麼在返回的新的對象中關於elementData還是指向了原Vector中elementData所指向的對象。這樣的話,相當於對另一個對象的操作會影響到原vector對象中elementData中的值,這顯然是不合理的.所以通過Arrays中的copyOf方法,將源數組中的值拷貝到新對象中,這樣在內存中就會存在兩個相同的副本,對對象操作之後不會影響彼此的數據。copyOf也是一個比較強大的函數,而Arrays也是一個經常使用到的工具類,可以大大的簡化工作,有興趣的可以去了解一下其細節,在以後的博文中應該也會學到。
10. addAll函數的實現
<pre name="code" class="java">public synchronized boolean addAll(Collection<? extends E> c) {
modCount++;
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityHelper(elementCount + numNew);
System.arraycopy(a, 0, elementData, elementCount, numNew);
elementCount += numNew;
return numNew != 0;
}
通過使用集合類中都存在的toArray()方法先將集合變爲相關對象的數組,然後對原始對象進行擴容調用<pre name="code" class="java">ensureCapacityHelper(elementCount + numNew);
使用系統拷貝,將源數組中的從0開始的numNew個元素拷貝到elementData中,從elementCount位置開始插入。
而集合中全部都有toArray方法,下面就直接看一下Vector中的toArray方法吧
11 toArray方法的實現
<span style="font-family:KaiTi_GB2312;font-size:14px;"></span><pre name="code" class="java">public synchronized Object[] toArray() {
return Arrays.copyOf(elementData, elementCount);
}
同樣是對於對象中數組的拷貝。12 擴容函數ensureCapacityHelper的實現
<span style="font-family:KaiTi_GB2312;font-size:14px;"></span><pre name="code" class="java">private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
<pre name="code" class="java"> private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
這部分代碼也沒有什麼好解釋的了,每一個集合類都有自己不同的擴容方法,根據集合的性能不同,使用了不同的方法,從這部分代碼能夠看到擴容的主要因子是capacityIncrement,容量增量。同時該擴容算法的容器增長率是呈線性增長的。
13.唯一一個實現的是Serilizable接口中的方法
<pre name="code" class="java">private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
final java.io.ObjectOutputStream.PutField fields = s.putFields();
final Object[] data;
synchronized (this) {
fields.put("capacityIncrement", capacityIncrement);
fields.put("elementCount", elementCount);
data = elementData.clone();
}
fields.put("elementData", data);
s.writeFields();
}
將對象中的字段以及值放入到流中,進行數據的傳輸。這裏也不在說明了,以後肯定還會遇到序列化接口的實現的。
14.listIterator的實現
上面就曾經說過,每一個集合類中都會存在一個迭代器,方便對集合中元素進行操作
<pre name="code" class="java">public synchronized Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
// Racy but within spec, since modifications are checked
// within or after synchronization in next/previous
return cursor != elementCount;
}
public E next() {
synchronized (Vector.this) {
checkForComodification();
int i = cursor;
if (i >= elementCount)
throw new NoSuchElementException();
cursor = i + 1;
return elementData(lastRet = i);
}
}
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
synchronized (Vector.this) {
checkForComodification();
Vector.this.remove(lastRet);
expectedModCount = modCount;
}
cursor = lastRet;
lastRet = -1;
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
/**
* An optimized version of AbstractList.ListItr
*/
final class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
public E previous() {
synchronized (Vector.this) {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
cursor = i;
return elementData(lastRet = i);
}
}
public void set(E e) {
if (lastRet == -1)
throw new IllegalStateException();
synchronized (Vector.this) {
checkForComodification();
Vector.this.set(lastRet, e);
}
}
public void add(E e) {
int i = cursor;
synchronized (Vector.this) {
checkForComodification();
Vector.this.add(i, e);
expectedModCount = modCount;
}
cursor = i + 1;
lastRet = -1;
}
}
一堆代碼以及包含了兩個內部實現類一個是Itr 正向迭代器,只能夠向下查詢。ListItr 雙向迭代器。通過兩個類似指針的標誌位來進行數據的查詢以及修改。
以上就是關於Vector的全部核心和有趣的方法。歡迎大家指正批評。