【问题标题】:Java - Issue retrieving value from hashtable [duplicate]Java - 从哈希表中检索值的问题[重复]
【发布时间】:2016-04-11 15:05:12
【问题描述】:

我创建了一个哈希表:

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

必需:字符串

找到:对象

【问题讨论】:

  • 不要使用原始类型。

标签: java hashtable


【解决方案1】:

getValue() 方法返回一个对象,而不是一个字符串,因此您得到了错误。你可以通过说来投射价值

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

【讨论】:

  • 太棒了...有效!
  • 另外值得注意的是,Hashtable 在这一点上已被弃用,OP 应该改用HashMap。为了避免这种铸造混乱,它应该被参数化为HashMap<String,String>
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2020-12-21
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多