HashObject之LinkedHashObjectMap(2)

本文介绍了一种基于双向链表的迭代器实现方法,并详细解释了如何通过覆盖父类方法来支持特定功能,如数据的老化机制及新数据插入到链表头部等操作。

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

private abstract class LinkedBaseHashObjectIterator implements Iterator<T> {
LinkedBaseHashObject nextObject = header.after;
LinkedBaseHashObject lastReturned = null;

/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
int expectedModCount = modCount;

public boolean hasNext() {
return nextObject != header;
}

public void remove() {
if (lastReturned == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();

LinkedHashObjectMap.this.remove(lastReturned);
lastReturned = null;
expectedModCount = modCount;
}

T nextObject() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (nextObject == header)
throw new NoSuchElementException();

LinkedBaseHashObject e = lastReturned = nextObject;
nextObject = e.after;
return (T)e;
}
}

private class ObjectIterator extends LinkedBaseHashObjectIterator {
public T next() { return (T)nextObject(); }
}

// These Overrides alter the behavior of superclass view iterator() methods
Iterator<T> newObjectIterator() { return new ObjectIterator(); }

/**
* 复写了父类的addObject方法,
* 支持双向链表功能,新添加的数据,会放在链表顶部。
* 支持老化数据的功能。
*/
void addObject(int hash, BaseHashObject object, int bucketIndex) {
LinkedBaseHashObject old = (LinkedBaseHashObject)table[bucketIndex];
LinkedBaseHashObject e = (LinkedBaseHashObject)object;
e.next = old;
table[bucketIndex] = e;
e.addBefore(header);
size++;
// Remove eldest entry if instructed, else grow capacity if appropriate
LinkedBaseHashObject eldest = header.after;
if (removeEldestEntry(eldest)) {
removeObjectForKey(eldest);
} else {
if (size >= threshold)
resize(2 * table.length);
}
}
/**
* 判断是否要老化数据
* @param eldest
* @return
*/
protected boolean removeEldestEntry(LinkedBaseHashObject eldest) {
if(log.isDebugEnabled())
{
log.debug("size():"+size()+";maxUserCount:"+maxUserCount);
}
if(size()> maxUserCount)
return true;
return false;
}

public int getMaxUserCount() {
return maxUserCount;
}
/**
* 设值缓存最大值
* @param maxUserCount
*/
public void setMaxUserCount(int maxUserCount) {
this.maxUserCount = maxUserCount;
if(log.isDebugEnabled())
{
log.debug("set maxUserCount:"+maxUserCount);
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值