转自: http://hi.baidu.com/onlylamplight/blog/item/2f55d4968803c16654fb9600.html
而在Hash的迭代上,看看他们是怎么循环的:
在HashTable的遍历上一般有两种方法:
1. for(Iterator itr = ht.keySet().iterator(); itr.hasNext();){
String key = (String) itr.next();
String value = (String) ht.get(key);
System.out.println(key+"--"+value);
}
通过对HashTable的Key的迭代,取出Key来提取HashTable中对应的值。我们知道数组通过下标来取值的时间复杂度为O(1),再来看看这个HashTable的keySet()方法:
private transient volatile Set<K> keySet = null; 这是keySet得定义 public Set<K> keySet() { if (keySet == null) keySet = Collections.synchronizedSet(new KeySet(), this); return keySet; } 返回一个同步的Key组成的Set,至于Collections.synchronizedSet(new KeySet(), this);这个方法,在api上好像找不到,我看了源码,是一个继承了SynchronizedCollection<E>内部类的方法,我没看明白具体算法怎么实现的,希望哪位N人能给指点一下,呵呵。 |
2. 通过HashTable提供的一个枚举方法,
Enumeration e1 = ht.elements();
while (e1.hasMoreElements()) {
System.out.println(e1.nextElement());
}
先看看HashTable的elements()方法,
public synchronized Enumeration<V> elements() { return this.<V>getEnumeration(VALUES); }
private <T> Enumeration<T> getEnumeration(int type) { if (count == 0) { return (Enumeration<T>)emptyEnumerator; } else { return new Enumerator<T>(type, false); } } Enumerator是一个内部类,主要是一个枚举类,取出这个了的nextElement方法来看:其实就是把私有的数组结构给从新定义一种模式,并提供统一的操作方法(个人理解)。 public T nextElement() { Entry<K,V> et = entry; int i = index; Entry[] t = table; /* Use locals for faster loop iteration */ while (et == null && i > 0) { et = t[--i]; } entry = et; index = i; if (et != null) { Entry<K,V> e = lastReturned = entry; entry = e.next; return type == KEYS ? (T)e.key : (type == VALUES ? (T)e.value : (T)e); } throw new NoSuchElementException("Hashtable Enumerator"); } |
当然我们也可以对Key进行枚举,然后一样的遍历。方法和上面的方法差不多
从HashTable的各种方法的synchronized来看,HashTable是线程安全的,而在HashTable的遍历上我个人更倾向于对Key的迭代,应为这样在存取元素的时候就是对数组的操作,这样更快。