说明
java原生的不能在遍历的时候删除,挺麻烦的,所以自己写了个可以在遍历的时候删除元素
总体性能其实比Hashtable好
使用上跟hashtable一致,遍历有点差别:
Hash hash = new Hash();
IIterator ii = hash.iterator();
while( ii.moveNext() )
{
print( ii.key, ii.value );
}
主类
package com.geom.hash;
import java.util.Hashtable;
/**
* 可以边遍历边删除
* 线程安全
*
* e.g:
*
Hash hash = new Hash();
IIterator ii = hash.iterator();
while( ii.moveNext() )
{
print( ii.key, ii.value );
}
*/
public class Hash<T, E>
{
private _KeyValueVO<T,E> _first;
private Hashtable<T, _KeyValueVO<T,E>> _dict;
public Hash ()
{
init();
}
private void init()
{
_first = new _KeyValueVO<T,E>(null, null);
_dict = new Hashtable<T, _KeyValueVO<T,E>>();
}
public int length()
{
synchronized (_dict)
{
return _dict.size();
}
}
public void Clear()
{
synchronized (_dict)
{
_dict.clear();
_first.next = null;
}
}
public void put( T key, E value )
{
if( key==null ) return;
_KeyValueVO<T,E> node = null;
synchronized (_dict)
{
node = _dict.get(key);
if( node==null )
{
node = new _KeyValueVO<T,E>( key, value );
_dict.put( key, node );
if( _first.next==null )
{
_first.next = node;
}
else
{
_first.next.prev = node;
node.next = _first.next;
_first.next = node;
}
node.prev = _first;
}
else node.value = value;
}
}
public E get( T key )
{
synchronized (_dict)
{
_KeyValueVO<T,E> node = _dict.get(key);
if( node != null )
{
return node.value;
}
return null;
}
}
public void remove( T key )
{
if( key==null ) return;
synchronized (_dict)
{
_KeyValueVO<T,E> node = _dict.get(key);
if( node != null )
{
_dict.remove( key );
node.key = null;
node.value = null;
node.isDelete = true;
node.prev.next = node.next;
if( node.next != null )
{
node.next.prev = node.prev;
}
}
}
}
public IIterator<T, E> iterator()
{
return new _HashIterator<T,E>( _dict, _first );
}
public boolean contains( Object value )
{
synchronized (_dict)
{
return _dict.contains( value );
}
}
public boolean containsKey( Object key )
{
synchronized (_dict)
{
return _dict.containsKey( key );
}
}
}
其他几个小类
package com.geom.hash;
public class IIterator<T, E>
{
public T key = null;
public E value = null;
public boolean moveNext()
{
return false;
}
}
package com.geom.hash;
class _HashIterator<T,E> extends IIterator<T, E>
{
private Object _lock = null;
private _KeyValueVO<T,E> _node;
public _HashIterator( Object lock, _KeyValueVO<T,E> node )
{
_lock = lock;
_node = node;
}
@Override
public boolean moveNext()
{
synchronized (_lock)
{
while( _node.next != null )
{
_node = _node.next;
if( !_node.isDelete )
{
key = _node.key;
value = _node.value;
return true;
}
}
key = null;
value = null;
return false;
}
}
}
package com.geom.hash;
class _KeyValueVO<T,E>
{
public boolean isDelete = false;
public T key;
public E value;
public _KeyValueVO<T,E> prev = null;
public _KeyValueVO<T,E> next = null;
public _KeyValueVO( T key, E value )
{
this.key = key;
this.value = value;
}
}