HashOjbect之HashObjectMap(5)

本文深入探讨了HashIterator的具体实现细节,包括其构造方法、hasNext方法及nextObject方法的工作原理。此外,还介绍了如何通过HashIterator遍历集合元素,并探讨了在并发修改情况下的异常处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private abstract class HashIterator implements Iterator<T> {
BaseHashObject next; // next entry to return
int expectedModCount; // For fast-fail
int index; // current slot
BaseHashObject current; // current entry

HashIterator() {
expectedModCount = modCount;
if (size > 0) { // advance to first entry
BaseHashObject[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
}

public final boolean hasNext() {
return next != null;
}

final T nextObject() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
BaseHashObject e = next;
if (e == null)
throw new NoSuchElementException();

if ((next = e.getNext()) == null) {
BaseHashObject[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
current = e;
return (T)e;
}

public void remove() {
if (current == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
BaseHashObject k = current;
current = null;
HashObjectMap.this.remove(k);
expectedModCount = modCount;
}

}

public Collection<T> objects() {
return new Objects();
}

private final class Objects extends AbstractCollection<T> {
public Iterator<T> iterator() {
return newObjectIterator();
}
public int size() {
return size;
}
public boolean contains(BaseHashObject o) {
return containsObject(o);
}
public void clear() {
HashObjectMap.this.clear();
}
}
public void putAll(Collection<BaseHashObject> objects) {
int numKeysToBeAdded = objects.size();
if (numKeysToBeAdded == 0)
return;

/*
* Expand the map if the map if the number of mappings to be added
* is greater than or equal to threshold. This is conservative; the
* obvious condition is (m.size() + size) >= threshold, but this
* condition could result in a map with twice the appropriate capacity,
* if the keys to be added overlap with the keys already in this map.
* By using the conservative calculation, we subject ourself
* to at most one extra resize.
*/
if (numKeysToBeAdded > threshold) {
int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
if (targetCapacity > MAXIMUM_CAPACITY)
targetCapacity = MAXIMUM_CAPACITY;
int newCapacity = table.length;
while (newCapacity < targetCapacity)
newCapacity <<= 1;
if (newCapacity > table.length)
resize(newCapacity);
}

for (Iterator<BaseHashObject> i = objects.iterator(); i.hasNext(); ) {
put(i.next());
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值