我遇到了使用數組實現非常簡單的HashTable的問題。問題在於HashTable
中的第一項總是AVAILABLE
。也許你們可以看到發生了什麼問題。這是HashTable
類:在Java中使用數組的簡單HashTable實現?
public class HashTable {
private Item[] data;
private int capacity;
private int size;
private static final Item AVAILABLE = new Item("Available", null);
public HashTable(int capacity) {
this.capacity = capacity;
data = new Item[capacity];
for(int i = 0; i < data.length; i++) {
data[i] = AVAILABLE;
}
size = 0;
}
public int size() {
return size;
}
public int hashThis(String key) {
return key.hashCode() % capacity;
}
public Object get(String key) {
int hash = hashThis(key);
while(data[hash] != AVAILABLE && data[hash].key() != key) {
hash = (hash + 1) % capacity;
}
return data[hash].element();
}
public void put(String key, Object element) {
if(key != null) {
size++;
int hash = hashThis(key);
while(data[hash] != AVAILABLE && data[hash].key() != key) {
hash = (hash + 1) % capacity;
}
data[hash] = new Item(key, element);
}
}
public Object remove(String key) {
// not important now.
throw new UnsupportedOperationException("Can't remove");
}
public String toString() {
String s = "<HashTable[";
for(int i = 0; i < this.size(); i++) {
s += data[i].toString();
if(i < this.size() - 1) {
s += ",";
}
}
s += "]>";
return s;
}
}
爲了更清楚,這是Item
類:
public class Item {
private String key;
private Object element;
public Item(String key, Object element) {
this.setKey(key);
this.setElement(element);
}
public String key() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object element() {
return element;
}
public void setElement(Object element) {
this.element = element;
}
public String toString() {
String s = "<Item(";
s += this.key() + "," + this.element() + ")>";
return s;
}
}
舉個例子:
HashTable ht = new HashTable(10);
ht.put("1", "a");
的toString(的輸出)把後必須是:
"<HashTable[<Item(1,a)>]>"
但我得到:
"<HashTable[<Item(Available,null)>]>"
更新:我也許應該提及的是,下一個項目被正確地放置和再下一個是不是一次。
循環從未停止現在:) – Loolooii 2012-03-31 18:08:09
@Loolooii在'toString'循環方法?每當你有一個不是'AVAILABLE'的單元格時,i'就會增加,所以它應該在'i = size'時停止。所以如果'size'設置正確(看起來是這樣)並且數組中有一個不等於'AVAILABLE'的元素,它應該停止。 – twain249 2012-03-31 18:10:03
是toString方法中的循環。我知道,它應該停止,但不知何故它不? – Loolooii 2012-03-31 18:12:28