介绍
和HashMap一样,Hashtable 也是一个散列表,它存储的内容是键值对(key-value)映射。 Hashtable 继承于Dictionary,实现了Map、Cloneable、java.io.Serializable接口。 Hashtable 的函数都是同步的,这意味着它是线程安全的。 它的key、value都不可以为null。此外,Hashtable中的映射不是有序的。
总结
public static void main ( String[ ] args) {
List< String> list = new ArrayList < > ( ) ;
list. add ( "Lions are the most mighty of all animals in Africa." ) ;
list. add ( "Those kids always have so much enthusiasm about studying." ) ;
list. add ( "Calligraphy is the art of beautiful handwriting." ) ;
for ( String str : list) {
System. out. println ( str) ;
}
System. out. println ( "-------------------------------------------" ) ;
for ( int i = list. size ( ) ; i-- > 0 ; ) {
System. out. println ( i) ;
System. out. println ( list. get ( i) ) ;
}
}
源码
构造函数
public Hashtable ( int initialCapacity, float loadFactor) {
if ( initialCapacity < 0 )
throw new IllegalArgumentException ( "Illegal Capacity: " +
initialCapacity) ;
if ( loadFactor <= 0 || Float. isNaN ( loadFactor) )
throw new IllegalArgumentException ( "Illegal Load: " + loadFactor) ;
if ( initialCapacity== 0 )
initialCapacity = 1 ;
this . loadFactor = loadFactor;
table = new Entry < ? , ? > [ initialCapacity] ;
threshold = ( int ) Math. min ( initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1 ) ;
}
成员方法
public synchronized int size ( ) {
return count;
}
public synchronized boolean contains ( Object value) {
if ( value == null) {
throw new NullPointerException ( ) ;
}
Entry< ? , ? > tab[ ] = table;
for ( int i = tab. length ; i-- > 0 ; ) {
for ( Entry< ? , ? > e = tab[ i] ; e != null ; e = e. next) {
if ( e. value. equals ( value) ) {
return true ;
}
}
}
return false ;
}
rehash函数
protected void rehash ( ) {
int oldCapacity = table. length;
Entry< ? , ? > [ ] oldMap = table;
int newCapacity = ( oldCapacity << 1 ) + 1 ;
if ( newCapacity - MAX_ARRAY_SIZE > 0 ) {
if ( oldCapacity == MAX_ARRAY_SIZE)
return ;
newCapacity = MAX_ARRAY_SIZE;
}
Entry< ? , ? > [ ] newMap = new Entry < ? , ? > [ newCapacity] ;
modCount++ ;
threshold = ( int ) Math. min ( newCapacity * loadFactor, MAX_ARRAY_SIZE + 1 ) ;
table = newMap;
for ( int i = oldCapacity ; i-- > 0 ; ) {
for ( Entry< K, V> old = ( Entry< K, V> ) oldMap[ i] ; old != null ; ) {
Entry< K, V> e = old;
old = old. next;
int index = ( e. hash & 0x7FFFFFFF ) % newCapacity;
e. next = ( Entry< K, V> ) newMap[ index] ;
newMap[ index] = e;
}
}
}
putAll函数
public synchronized void putAll ( Map< ? extends K , ? extends V > t) {
for ( Map. Entry< ? extends K , ? extends V > e : t. entrySet ( ) )
put ( e. getKey ( ) , e. getValue ( ) ) ;
}
containsKey函数
public synchronized boolean containsKey ( Object key) {
Entry< ? , ? > tab[ ] = table;
int hash = key. hashCode ( ) ;
int index = ( hash & 0x7FFFFFFF ) % tab. length;
for ( Entry< ? , ? > e = tab[ index] ; e != null ; e = e. next) {
if ( ( e. hash == hash) && e. key. equals ( key) ) {
return true ;
}
}
return false ;
}