Native
Native

Reputation: 177

Getting a value from a map (Using Java 1.4)

I am currently working on some old legacy application, and must use Java 1.4 which has been EOL for several years now. I need to get a value from a map. My map looks like this:

Key     |  Value
---------------
String1 | int1
String2 | String6
String3 | Float1
String4 | String7
String5 | Object1

I tried the following, but I keep getting a null

String myVal = (String) map.get(String2);

Is it possible to get a value without using an Iterator?

Upvotes: 0

Views: 877

Answers (1)

Simone Gianni
Simone Gianni

Reputation: 11662

You should get the value in the way you reported, this is totally right :

String myVal = (String) map.get("myKey");

As long as the map has that key inside.

The problem, with the map scheme you reported, is that the map could contain String, Float or other value types, so casting it directly to String is dangerous. You should check the value type :

Object myValObj = map.get("myKey");
if (myValObj instanceof String) {
  // Handle the string
} else if (myValObj instanceof Float) {
  // Handle the float
} // ....

Upvotes: 1

Related Questions