Java-从哈希表中检索值的问题

Java-从哈希表中检索值的问题,java,hashtable,Java,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(entr

我创建了一个哈希表:

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()

必需:字符串

found:Object

方法
getValue()
返回的是一个对象,而不是字符串,因此会出现错误。你可以通过说

String nextHopInt = (String) entry.getValue();

如果RHS是向下转换(对象->字符串),则必须显式转换RHS


太棒了…真管用!同样值得注意的是,
Hashtable
在这一点上非常不受欢迎,OP应该使用
HashMap
。为了避免这种类型转换混乱,应该将其参数化为
HashMap
不使用原始类型。
String nextHopInt = (String)entry.getValue();