배열을 사용하여 매우 간단한 HashTable을 구현하는 데 문제가 있습니다. 문제는 HashTable
에있는 첫 번째 항목은 항상 AVAILABLE
입니다. 어쩌면 너희들은 무엇이 잘못되었는지 알 수있을 것이다.Java에서 배열을 사용하는 간단한 HashTable 구현?
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;
}
}
는 예를 들어 줄 :
더 명확성을 위해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
클래스 :
HashTable ht = new HashTable(10);
ht.put("1", "a");
toString (의 출력)을 가하고 후이는 HashTable
클래스 다음과 같아야합니다 :
"<HashTable[<Item(1,a)>]>"
하지만 내가 얻을 :
"<HashTable[<Item(Available,null)>]>"
업데이트 :은 아마 다음 항목이 제대로 넣어 도착, 그 후 하나가 다시 아니라고 언급해야한다.
루프는 결코 멈추지 않는다 지금 : – Loolooii
@Loolooii은'toString'에서 루프 방법? 'AVAILABLE'이 아닌 셀을 가질 때마다'i'가 증가하므로'i = size' 때 멈춰야합니다. 따라서'size'가 올바르게 설정되고 (있는 것처럼 보이고) 배열에 AVAILABLE과 같지 않은 요소가 있으면 정지해야합니다. – twain249
예, toString 메서드의 루프입니다. 나도 알아, 그만둬야 해, 근데 어떻게 든 그럴 수 없어?! – Loolooii