哈希表之我见

    哈希表将原本需要存储的数据总量分散到它的每一个容器中,以此来提高查找效率。而具体如何分散到容器中,则是随应用场合而变。我实现的Hash表采用了最简易的一种映射关系:取模。

    需要根据要处理的数据的数量级,来确定初始的容器数量。我拟定的数量级是1000000(百万),并选择初始容器数量为1000。我使用一维数组来作为Hash表的容器,当发生冲突时就在数组内不断挂链,直到需要rehash

public class Hash {
	private LinkedList<User> ll[] = new LinkedList[1000];   //Hash表容器大小
	
	public Hash()
	{
	}
	
	
	public int doHash(int key)
	{
		//采用最简易的规则:取模
		int keyId = key%ll.length;
		return keyId;
	}
	
	
	public void insert(User u)
	{
		int key = doHash(u.getId());
		if(ll[key] == null){
			ll[key] = new LinkedList<User>();
			ll[key].add(u);
		}else{
			ll[key].getLast().setNext(u);
			ll[key].add(u);
		}
	}

	
	public boolean find(int id)
	{
		int temp = doHash(id);
		if(ll[temp] != null){
			User u = ll[temp].get(0);
			while(u != null){
				if(u.getId() == temp){
					System.out.println("Find it!");
					return true;
				}else{
					u = u.getNext();
				}
			}
		}
		System.out.println("用户不存在");
		return false;
	}
	
	
}
 

 

猜你喜欢

转载自285747430.iteye.com/blog/2202530