它是用一個散列函數把關鍵字 映射到散列表中的特定位置。 在理想情況下,如果元素e 的關鍵字為k,散列函 數為f,那么e 在散列表中的位置為f (k)。要搜索關鍵字為k 的元素,首先要計算出f (k),然后看 表中f (k)處是否有元素。如果有,便找到了該元素。如果沒有,說明該字典中不包含該元素。 在前一種情況中,如果要刪除該元素,只需把表中f (k)位置置為空即可。在后一種情況中,可 以通過把元素放在f (k)位置以實現插入。 此例是一個理想情況下的散列表,不考慮關鍵字重復的情況
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; } }
新聞熱點
疑難解答