我已经在 java 中实现了一个 hashtale,但我需要优化代码。我认为我有很多循环。如何“减少”循环次数?问题是,当我删除一个元素时,我必须重新哈希表,然后我有鬃毛跳跃 beetwen delete() 和 put()。我不想要任何代码示例,只是指导,因为这是一个学校练习 :)
谢谢
这是我的功能:
public void put(String key, Character val) {
int hashValue = hash(key);
if(val == '\r'){
delete(key);
}
else {
while(keys[hashValue] != null) {
if(keys[hashValue].equals(key)) {
break;
}
hashValue = (hashValue + 1) % M ;
}
keys[hashValue] = key ;
vals[hashValue] = val;
N++;
}
}
public Character get(String key) {
int hashValue = hash(key);
while(keys[hashValue] != null) {
if(keys[hashValue].equals(key)){
return vals[hashValue];
}
hashValue = (hashValue+1) % M;
}
return null;
}
public void delete(String key) {
int hashValue = hash(key) ;
String tempkey;
Character tempval;
boolean deleted = false;
while(keys[hashValue] != null){
if(keys[hashValue].equals(key)){
keys[hashValue] = null;
vals[hashValue] = null;
deleted = true;
N--;
if(keys[(hashValue + 1) % M] == null){
break;
}
}
else if(deleted = true){
tempkey = keys[hashValue];
tempval = vals[hashValue];
keys[hashValue] = null;
vals[hashValue] = null;
N--;
put(tempkey, tempval);
}
hashValue = (hashValue +1) % M;
}
return;
}