1、
盡可能的用位運算,比如HashMap的查找Entry<K, V> [] table下標的操作
static int indexFor(int h, int length) {
return h & (length-1);
}
2、
對于java.utl.ArrayList、HashMap、LinkedHashMap、HashSet、LinkedSet等的new操作最好指定所需大小。 2.1、對于ArrayList來說add操作有一行代碼為:ensureCapacity(size + 1);具體實現如下:
1 public void ensureCapacity(int minCapacity) {
2 modCount++;
3 int oldCapacity = elementData.length;
4 if (minCapacity > oldCapacity) {
5 Object oldData[] = elementData;
6 int newCapacity = (oldCapacity * 3)/2 + 1;
7 if (newCapacity < minCapacity)
8 newCapacity = minCapacity;
9 // minCapacity is usually close to size, so this is a win:
10 elementData = Arrays.copyOf(elementData, newCapacity);
11 }
12 }
可以看出,如果ArrayList超出原先的容量,需要擴容的時候,是先new一個數組,然后把原來的數組拷貝到新數組中。所以如果原先可以確定容量的話,采用public ArrayList(int initialCapacity)構造方法。
2.2、對于HashMap來說put操作,如果在原有的key中沒有找到匹配項,則需要把key加入到Entry<>[] table中。 具體代碼如下:
1 void addEntry(int hash, K key, V value, int bucketIndex) {
2 Entry<K,V> e = table[bucketIndex];
3 table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
4 if (size++ >= threshold)
5 // 當size++ >= 負載因子時,進行擴容操作
6 resize(2 * table.length);
7 }
resize(int newCapacity)代碼如下:
1 void resize(int newCapacity) {
2 Entry[] oldTable = table;
3 int oldCapacity = oldTable.length;
4 if (oldCapacity == MAXIMUM_CAPACITY) {
5 threshold = Integer.MAX_VALUE;
6 return;
7 }
8 // 需要重新new 一個Entry數組
9 Entry[] newTable = new Entry[newCapacity];
10 transfer(newTable);
11 table = newTable;
12 threshold = (int)(newCapacity * loadFactor);
13 }
這里調用一個方法transfer(Entry[] newTable)其代碼如下:
1 void transfer(Entry[] newTable) {
2 Entry[] src = table;
3 int newCapacity = newTable.length;
4 // 對Entry[] src進行循環,把舊的Entry[]拷貝到新的Entry[]中
5 for (int j = 0; j < src.length; j++) {
6 Entry<K,V> e = src[j];
7 if (e != null) {
8 // 把src賦值為null,為了GC操作的時候,回收原來的Entry[]
9 src[j] = null;
10 // 對table[j]的鏈表進行循環
11 do {
12 Entry<K,V> next = e.next;
13 // 計算在新的Entry[]數組的下標
14 int i = indexFor(e.hash, newCapacity);
15
16 e.next = newTable[i];
17 newTable[i] = e;
18 e = next;
19 } while (e != null);
20 }
21 }
22 }
2.3、HashSet、LinkedSet、LinkedMap與上同
3、
數組復制的時候,用System.arraycopy方法,比如2.1中的ensureCapacity(int minCapacity)方法,調用的Arrays.copyOf方法。在Array.copy中調用了System.arraycopy,其代碼如下:
1 public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
2 T[] copy = ((Object)newType == (Object)Object[].class)
3 ? (T[]) new Object[newLength]
4 : (T[]) Array.newInstance(newType.getComponentType(), newLength);
5 System.arraycopy(original, 0, copy, 0,
6 Math.min(original.length, newLength));
7 return copy;
8 }
4、待更新
posted on 2011-08-16 22:15
showsun 閱讀(704)
評論(0) 編輯 收藏 所屬分類:
J2SE