gpt4 book ai didi

java - 在 Java 中使用数组的简单 HashTable 实现?

转载 作者:搜寻专家 更新时间:2023-11-01 03:11:07 25 4
gpt4 key购买 nike

我在使用数组实现非常简单的 HashTable 时遇到了问题。问题是放在 HashTable 中的第一个项目总是 AVAILABLE。也许你们可以看到出了什么问题。这是 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)>]>"

更新:我可能应该提一下,下一项已正确放置,而之后的一项则不是。

最佳答案

我认为问题出在您的 toString 方法中。你循环 0 - size when size = 1 所以你只打印出 hashTable 问题中的第一个值是你的哈希表中的第一个值不是一个真正的值它是一个 AVAILABLE 你必须做这样的事情

编辑:对不起,我忘了移动索引。

public String toString() {
String s = "<HashTable[";
int i = 0;
int count = 0;
while(count < this.size()) {

//Skip the AVAILABLE cells
if(data[i] == AVAILABLE) {
i++;
continue;
}

s += data[i].toString();
if(count < this.size() - 1) {
s += ",";
}
count++;
}
s += "]>";
return s;
}

关于java - 在 Java 中使用数组的简单 HashTable 实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9958216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com