我正在使用字典中的update方法,但无法找到解决方案。 所以这里有字典类:
public class Dictionary implements IDictionary{
public class ObjectDictionary{
//public boolean isFull=false;
public Object key;
public Object value;
public void setValue(Object value){
this.value = value;
}
public Object getValue(){
return value;
}
public ObjectDictionary(Object k,Object v){
this.key=k;
this.value=v;
}
}
//......(other methods)
public void put(Object k,Object v){
//ObjectDictionary ob = new ObjectDictionary();
if (elems.length == nrElem){
resize();
}
elems[nrElem] = new ObjectDictionary(k,v);
elems[nrElem].key=k;
elems[nrElem].value=v;
//elems[i].isFull=true;
nrElem++;
}
public void update(Object k, Object v, Object newV){
ObjectDictionary ob = new ObjectDictionary(k,v);
if (lookUp(k) !=null){
ob.setValue(newV);
}
}
public Object lookUp(Object k){
for(int i=0; i<elems.length;i++)
if(elems[i].key.equals(k)){
return elems[i].value;
}
return null;
}
}
主要:
public class Start {
public static void main(String[] args){
IDictionary d = new Dictionary();
d.put("a",7);
d.put("b", 2);
d.update("a",7, 4);
//System.out.println(d.size());
System.out.println(d.lookUp("a"));
}
}
我当时认为lookUp(k)可能存在问题,因为它返回值,然后检查字典中是否存在,然后焦急地找不到密钥,但我不知道。这有什么问题? 我也试图在这里取代:
ObjectDictionary ob = new ObjectDictionary(k,v)
v值为0但没有成功。有什么建议?谢谢。
答案 0 :(得分:0)
看起来你没有更新参考资料:
public void update(Object k, Object v, Object newV){
ObjectDictionary ob = new ObjectDictionary(k,v);
if (lookUp(k) !=null){
ob.setValue(newV);
}
}
试试这个
public Object getEntry(Object k){
for(int i=0; i<elems.length;i++)
if(elems[i].key.equals(k)){
return elems[i];
}
return null;
}
public void update(Object k, Object v, Object newV){
Object entry = getEntry(k)
if (entry !=null){
entry.setValue(newV);
}
}