Java - 从哈希表中检索值的问题
Java - Issue retrieving value from hashtable
我创建了一个哈希表:
Hashtable next_hop = new Hashtable();
我插入值 next_hop.put("R1","local") 等等...
哈希表如下所示:
{R5=R5, R4=R2, R3=R2, R2=R2, R1=Local}
现在我尝试从键中检索值,如下所示:
String endPoint = "R1";
for (Object o: next_hop.entrySet()) {
Map.Entry entry = (Map.Entry) o;
if(entry.getKey().equals(endPoint)){
String nextHopInt = entry.getValue();
}
}
我收到以下错误:
错误:不兼容的类型
String nextHopInt = entry.getValue();
必填:字符串
找到:对象
方法 getValue()
returns 一个对象,而不是一个字符串,因此出现错误。您可以通过说
来转换值
String nextHopInt = (String) entry.getValue();
如果 RHS 是向下转换(对象 -> 字符串),则必须显式转换 RHS。
String nextHopInt = (String)entry.getValue();
我创建了一个哈希表:
Hashtable next_hop = new Hashtable();
我插入值 next_hop.put("R1","local") 等等...
哈希表如下所示:
{R5=R5, R4=R2, R3=R2, R2=R2, R1=Local}
现在我尝试从键中检索值,如下所示:
String endPoint = "R1";
for (Object o: next_hop.entrySet()) {
Map.Entry entry = (Map.Entry) o;
if(entry.getKey().equals(endPoint)){
String nextHopInt = entry.getValue();
}
}
我收到以下错误:
错误:不兼容的类型
String nextHopInt = entry.getValue();
必填:字符串
找到:对象
方法 getValue()
returns 一个对象,而不是一个字符串,因此出现错误。您可以通过说
String nextHopInt = (String) entry.getValue();
如果 RHS 是向下转换(对象 -> 字符串),则必须显式转换 RHS。
String nextHopInt = (String)entry.getValue();