转换为String和String.valueOf之间的差异 [英] Difference between casting to String and String.valueOf

查看:163
本文介绍了转换为String和String.valueOf之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之间有什么区别?

  Object foo =something 
String bar = String.valueOf(foo);

  Object foo =something; 
String bar =(String)foo;


解决方案

实际上是一个字符串:

  Object reallyAString =foo; 
String str =(String)reallyAString; //工作。

当对象是其他对象时,它将无法工作:

  Object notAString = new Integer(42); 
String str =(String)notAString; // will throw a ClassCastException

String.valueOf() 将尝试将你传递给它的任何内容转换为 String 。它使用对象的 42 )和对象( new Integer(42) http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString%28%29> toString() ):

  
str = String.valueOf(new Integer(42)); // str将保存42
str = String.valueOf(foo); // str将持有foo
对象nullValue = null;
str = String.valueOf(nullValue); // str将持有null

特别注意最后一个例子:passing null String.valueOf()将返回字符串null p>

What is the difference between

Object foo = "something";
String bar = String.valueOf(foo);

and

Object foo = "something";
String bar = (String) foo;

解决方案

Casting to string only works when the object actually is a string:

Object reallyAString = "foo";
String str = (String) reallyAString; // works.

It won't work when the object is something else:

Object notAString = new Integer(42);
String str = (String) notAString; // will throw a ClassCastException

String.valueOf() however will try to convert whatever you pass into it to a String. It handles both primitives (42) and objects (new Integer(42), using that object's toString()):

String str;
str = String.valueOf(new Integer(42)); // str will hold "42"
str = String.valueOf("foo"); // str will hold "foo"
Object nullValue = null;
str = String.valueOf(nullValue); // str will hold "null"

Note especially the last example: passing null to String.valueOf() will return the string "null".

这篇关于转换为String和String.valueOf之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆