2

I have a hashtable created:

Hashtable next_hop = new Hashtable();

I insert values like next_hop.put("R1","local") and so on...

The hashtable looks like this:

{R5=R5, R4=R2, R3=R2, R2=R2, R1=Local}

Now I try to retrieve the values from the keys as follows:

String endPoint = "R1";
for (Object o: next_hop.entrySet()) {
   Map.Entry entry = (Map.Entry) o;
   if(entry.getKey().equals(endPoint)){
       String nextHopInt = entry.getValue();
    }
}

i get the following error: error: incompatible types String nextHopInt = entry.getValue();

required: String

found: Object

hnvasa
  • 830
  • 4
  • 13
  • 26

2 Answers2

6

The method getValue() returns an object, not a string, hence the error you are getting. You can cast the value by saying

String nextHopInt = (String) entry.getValue();
Rabbit Guy
  • 1,840
  • 3
  • 18
  • 28
  • 2
    awesome...that works! – hnvasa Apr 11 '16 at 15:10
  • 6
    Also worth noting that `Hashtable` is very deprecated at this point and OP should be using `HashMap` instead. And to avoid this casting mess, it should be parameterized as `HashMap` – TayTay Apr 11 '16 at 15:10
0

You have to explicitly cast the RHS if it is a downcast (Object -> String).

String nextHopInt = (String)entry.getValue();
James Wierzba
  • 16,176
  • 14
  • 79
  • 120