| Author |
importance of String.valueOf(Object)
|
ajse ruku
Ranch Hand
Joined: May 06, 2005
Posts: 192
|
|
Hi ,
I have following code.
String test=(String)map.get("x");
Some one suggested me to use
String test=String.valueOf(map.get("x"))
Do we have any advantage of doing this?
regards,
Ajse
|
 |
Mike Simmons
Ranch Hand
Joined: Mar 05, 2008
Posts: 2816
|
|
Well, what's in the map?
Your first code assumes that the values in the map are all Strings, and so casts to String. If you're right, this is fine. But if any values in teh map are not Strings, the cast fails, and you get an exception.
The second code makes no assumptions about whether the values are Strings or something else. It just calls toString() on any object it finds. It also handles null.
If you're using JDK 5 or later, the map should be declared using generics, and so you should know exactly what type is in it. Then no guessing or casting is necessary. If you have
then later you can use
and there's no need for a cast - the compiler knows that the value is already a String. Or possibly null.
However if you have
then later you should use
Here the only advantage of using valueOf() instead of toString() is that valueOf() handles null without throwing an exception.
|
 |
ajse ruku
Ranch Hand
Joined: May 06, 2005
Posts: 192
|
|
|
There will be objects in the map.
|
 |
Mohamed Sanaulla
Bartender
Joined: Sep 08, 2007
Posts: 2946
|
|
Cast can fail at times. So using valueOf would be safer. But how is the map declared like? If its something like: Map<String,String> then you need to worry about casting or using valueOf.
Update: Ok, I was late this time
|
Mohamed Sanaulla | My Blog
|
 |
 |
|
|
subject: importance of String.valueOf(Object)
|
|
|