空值字符串串联
我有以下代码
System.out.println("" + null);
并且输出为 。
Java如何在字符串连接中发挥作用?null
我有以下代码
System.out.println("" + null);
并且输出为 。
Java如何在字符串连接中发挥作用?null
因为Java将表达式转换为类似于"A String" + x
"A String" + String.valueOf(x)
实际上,我认为它可能使用s,因此:StringBuilder
"A String " + x + " and another " + y
决心提高效率
new StringBuilder("A String ")
.append(x)
.append(" and another ")
.append(y).toString()
这使用字符串生成器(对于每种类型)上的方法,这些方法可以正确处理append
null
Java在幕后使用。StringBuilder.append( Object obj )
不难想象它的实施。
public StringBuilder append( Object obj )
{
if ( obj == null )
{
append( "null" );
}
else
{
append( obj.toString( ) );
}
return this;
}