If what you have in "o" is a string, then there isnβt much difference (probably the cast is faster, but this is a thing of the VM / Library implementation).
If "o" may not be a string, but it is assumed to be a String, then the cast is what you want (but you must force the method to take a string instead of an object).
If "o" can be any type, then you should use toString, but be sure to check the null value first.
void foo(final Object o) { final String str;
or
void foo(final Object o) { final String str; // if you are 100% sure that o is not null then you can get rid of the else if(o != null) { str = o.toString(); } }
I would prefer the code of the latter:
void foo(final Object o) { final String str; if(o == null) { throw new IllegalArgumentException("o cannot be null"); } str = o.toString(); }
TofuBeer Mar 24 '09 at 7:08 2009-03-24 07:08
source share