哈希表
查找、插入均为O(1)。
注意两点:
(1)对于静态集,可以构造没有冲突的hash函数;对于动态集合(可以插入、删除),则很难。
(2)尽量找到一个好的hash函数,例如:md5等。
(3)在产生collsion之后,要解决冲突, 比如链地址法(拉链,插入时插在表头)。
(4)装载因子(load factor):
a. 在Java中的HashMap中是这样写的:
As a general rule, the
default
load factor (.
75
) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected
in
most of the operations of the HashMap
class
, including
get
and put). The expected number of entries
in
the map and its load factor should be taken into account when setting its initial capacity, so
as
to minimize the number of rehash operations. If the initial capacity
is
greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.
当LF > 0.75时,要进行rehash。
b. 在Java的编译器GJC1.4中,当LF > 2/3时,进行dble,代码如下:
/** */
/**
* @(#)Hashtable.java 1.13 03/01/23
*
* Copyright 2003 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tools.javac.v8.util;
/** */ /**
* A generic simplified version of java.util.Hashtable.
*/
public class Hashtable ... {
...
private void dble() ...{
hashSize = hashSize << 1;
hashMask = hashSize - 1;
limit = limit << 1;
Entry[] oldtable = table;
table = new Entry[hashSize];
for (int i = 0; i < oldtable.length; i++) ...{
for (Entry e = oldtable[i], next = null; e != null; e = next) ...{
next = e.next;
int ix = e.hash & hashMask;
e.next = table[ix];
table[ix] = e;
}
}
}
...
}
* @(#)Hashtable.java 1.13 03/01/23
*
* Copyright 2003 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tools.javac.v8.util;
/** */ /**
* A generic simplified version of java.util.Hashtable.
*/
public class Hashtable ... {
...
private void dble() ...{
hashSize = hashSize << 1;
hashMask = hashSize - 1;
limit = limit << 1;
Entry[] oldtable = table;
table = new Entry[hashSize];
for (int i = 0; i < oldtable.length; i++) ...{
for (Entry e = oldtable[i], next = null; e != null; e = next) ...{
next = e.next;
int ix = e.hash & hashMask;
e.next = table[ix];
table[ix] = e;
}
}
}
...
}