散列表 hash


分离链接法

public class SeparateChainingHashTable<AnyType> {

	//构造器
	public SeparateChainingHashTable(){
		this(DEFAULT_TABLE_SIZE);
	}
	public SeparateChainingHashTable(int size){
		theLists = new LinkedList[nextPrime(size)];
		for(int i = 0; i < theLists.length; i++){
			theLists[i] = new LinkedList<AnyType>();
		}
	}
	
	public void insert(AnyType x){
		List<AnyType> whichList = theLists[myhash(x)];
		if(!whichList.contains(x)){
			whichList.add(x);
			
			if(++currentSize > theLists.length){
				rehash();
			}
		}
	}
	
	public void remove(AnyType x){
		List<AnyType> whichList = theLists[myhash(x)];
		if(whichList.contains(x)){
			whichList.remove(x);
			currentSize--;
		}
	} 
	
	public boolean contains(AnyType x){
		List<AnyType> whichList = theLists[myhash(x)];
		return whichList.contains(x);
	}
	
	public void makeEmpty(){
		for(int i = 0; i < theLists.length; i++){
			theLists[i].clear();
		}
		currentSize = 0;
	}
	
	private static final int DEFAULT_TABLE_SIZE = 101;
	
	private List<AnyType>[] theLists;
	private int currentSize;
	
	private void rehash(){
		List<AnyType>[] oldLists = theLists;
		
		theLists = new List[nextPrime(2*theLists.length)];
		for(int j = 0; j < theLists.length; j++){
			theLists[j] = new LinkedList<AnyType>();
		}
		
		currentSize = 0;
		for(int i = 0; i < oldLists.length; i++){
			for(AnyType item :oldLists[i]){
				insert(item);
			}
		}
	}
	
	private int myhash(AnyType x){
		//散列表只对遵守确定协议的那些对象工作,即这些对象:
		//1, 必须提供适当equals方法
		//2, 必须提供返回一个int型的hashCode方法
		int hashVal = x.hashCode();
		
		hashVal %= theLists.length;
		if(hashVal < 0){
			hashVal += theLists.length;
		}
		return hashVal;
	}
	
	private static int nextPrime(int n){
		if(n%2 == 0){
			n++;
		}
		for(; !isPrime(n); n+=2){
			;
		}
		
		return n;
	}
	private static boolean isPrime(int n){
		if(n == 2 || n ==3){
			return true;
		}
		if(n == 1 || n%2 == 0){
			return false;
		}
		return true;
	}
}

未完待续

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值