散列表 hash
2013-08-08 22:27
190 查看
分离链接法
未完待续
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; } }
未完待续
相关文章推荐
- Hash查找,散列查找
- hash,分离链接法,探测散列表(二次探测),再散列的代码
- Perl语言入门--5--散列、hash
- 二次探查再散列Hash表的C++实现
- Oracle 散列(HASH)聚簇表
- 算法导论第十一(11)章散列(Hash)表
- Redis入门(四)散列Hash
- 数组 链表 散列(hash)
- Redis学习2--散列hash
- Java散列集Set 树集TreeSet HashSet LinkedHashSet SortedSet NavigableSet
- 散列(HASH)---内含Java HashMap理解
- 使用openssl中的EVP通用加密算法接口的之--hash散列运算测试例子
- redis基本结构(2)------散列(hash)
- HashMap,Hash优化与高效散列
- Effective STL- 熟悉非标准的散列容器(hash 容器)
- Redis 散列(Hash)介绍与基本操作
- Redis数据类型之散列(hash)
- Redis从基础命令到实战之散列类型(Hash)
- 非对称算法,散列(Hash)以及证书的那些事