浏览 2395 次
锁定老帖子 主题:自己动手写数据结构之散列表
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2012-04-06
【散列表】
public class HashList { private String[] table; private int size; private int threshold; private static final int INITIAL_CAPACITY = 10; private static final int SIZE_INCREASE = 10; private static final float DEFAULT_LOAD_FACTOR = 0.75f; public HashList(){ threshold = (int)(INITIAL_CAPACITY*DEFAULT_LOAD_FACTOR); table = new String[INITIAL_CAPACITY]; } public HashList(String[] table){ this.table = table; } /** * Get the actual size of the list * @return */ public int size(){ return size; } /** * for test * @return */ public String[] getElements(){ return table; } public boolean contains(String element) { if (element == null) { return false; } if (element.equals(table[getIndex(element)])) { return true; } return false; } public void add(String element){ int index = getIndex(element); if(size>threshold){ resize(); } table[index] = element; size++; } //private methods /** * resize the array */ private void resize(){ String[] newArray = new String[table.length+SIZE_INCREASE]; for(int i=0;i<table.length;i++){ newArray[i] = table[i]; } table = newArray; threshold = (int)(table.length*DEFAULT_LOAD_FACTOR); } /** * get the index of the element * @param element * @return */ public int getIndex(String element) { return (element.hashCode() & 0x7FFFFFFF) % table.length; } }
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |