好的,我一直有问题。在我当前的项目中,我在我的"哈希表",(链接列表数组)中添加了一个单词,并且我添加了一个单词,然后检查所述工作以查看它是否已添加。我可以从System out告诉它已被添加,但是检查/读取部分失败了。任何帮助都会很棒。
测试代码
public void testAdd(){
assertEquals(false, commonWords.checkWord("applicable"));
commonWords.add("applicable");
assertEquals(true, commonWords.checkWord("applicable"));
//restore commonWords back to original
commonWords.create(commonFile);
}
添加代码
public int add(HashableWordInterface s) {
System.out.println("added"+s.hashCode()%TABLE_SIZE+" "+s.getString());
table[s.hashCode()%TABLE_SIZE].put(s.getString());
size++;
return size;
}
public void put(String key) {
for (Node curr = first; curr != null; curr = curr.next) {
if (key.equals(curr.word)) {
System.out.println("oops");
return; //search hit: return
}
}
first = new Node(key, first); //search miss: add new node
}
public void add(String word) {
HashableWord t= new HashableWord(word.toLowerCase().trim());
derp.add(t);
}
阅读/检查代码
public boolean checkWord(String input) {
input = input.toLowerCase();
HashableWord t= new HashableWord(input);
return derp.contains(t);
}
public boolean contains(HashableWordInterface s) {
String input= s.getString();
input = input.toLowerCase();
System.out.println(table[(s.hashCode()%TABLE_SIZE)].get(input));
return table[(s.hashCode()%TABLE_SIZE)].get(input);
}
public boolean get(String in) { //return key true if key exists
Node next = first;
while (next != null) {
if (next.word.equals(in)) {
return true;
}
next = next.next;
}
return false;
}
和哈希码本身
public int hashCode(String word){
final int HASH_MULTIPLIER = 31;
int h = 0;
for (int i = 0; i < word.length(); i++) {
h = HASH_MULTIPLIER * h + word.charAt(i);
}
System.out.println(h%(1300/3)+" "+word);
return h;
}
请注意,这些方法并非都在同一个类中,但至少在子类中 编辑:我忘记了一些代码
HashTable derp;
public Dictionary() {
derp= new HashTable();
}
public class HashTable implements HashTableInterface {
private final static int TABLE_SIZE = 1300/3;
Bucket[] table;
private int size ;
public HashTable() {
table = new Bucket[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++) {
table[i] = new Bucket();
}
}