开发者

Is it better to do toString() or cast the Object to String [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

(String) or .toString()?

I have an Object. Is it better to do like this

 final String params开发者_StackOverflow社区 = myObject.toString();

or

 final String params =(String)myObject;


ToString will work with all objects (as long as they are not null). If you cast to a String then the object has to be a String, otherwise it will fail. So my guess is that you want a toString() call, but it depends on what you want to do!


It depends what you're trying to do.

When you cast the object to string like (String)myObject you're actually trying to convert the object to a string, so you can get the class cast exception.

However, when calling myObject.toString you get a logical representation in String format of that object and it depends on implementation of toString() method of that object.


When you use (String)request.getAttribute("buyertosellerpersoni d") request.getAttribute("buyertosellerpersonid") returns you an object which you typecast into a String object. Incase the object that you're trying to typecast isn't actually a String object, you'll get a ClassCastException. Make sure that you always set the attribute "buyertosellerpersonid" with a String value.

When you use request.getAttribute("buyertosellerpersonid").toString() the toString() method of the object returned by request.getAttribute("buyertosellerpersonid") is called.

Now it depends on the implementation of the toString() method of this object as to what it will return. If it is a string that you've put in the attribute "buyertosellerpersonid" then you'll get the String value. If it is anything else, then you'll get the unsigned hexadecimal representation of its hashcode.

It is always a better idea to typecast the object. This makes sure that you always get the correct object, and it will throw an exception otherwise. You must catch such exceptions to ensure correct functioning of your program.


(String)myObject works fine only if myObject is instance of class String.

In the case of myObject.toString() calls toString() method of class myObject. toString method is inherited from Object class.


It is totally irrelevant and pointless performance questions to worry about.

Who reallycares? The chances of it making any difference to your overall algorithm are vanishingly small. Use the one that makes most sense in your code.

One more thing , There is a difference in the two, you can only cast if object really is a String object whereas you can call toString() on any Object, not just a String.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜