有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么下面的代码不工作(StringBuffer.toString!=null)

我对弦的世界还不熟悉

我的代码如下所示

StringBuffer buffer=new StringBuffer();
String addressLineOne=null;
buffer.append(addreeLineOne);
if(buffer.toString!=null)
{
 system.out.println("Not NULL");
}

结果:非空; (buffer.toString!=null)==true

即使我将null附加到缓冲区,我也无法通过null检查来识别它, 代码打印不为空

为什么会这样


共 (3) 个答案

  1. # 1 楼答案

    public StringBuffer append(Object obj)
    

    Appends the string representation of the Object argument.

    The overall effect is exactly as if the argument were converted to a string by the method String.valueOf(Object), and the characters of that string were then appended to this character sequence

    因此addressLineOne将被转换为String表示,然后再附加到缓冲区

    According to JLS, Section 15.18.1.1

    If the reference is null, it is converted to the string "null"

    隐式地,这将发生:String.valueOf(addressLineOne)//将给您一个值为“null”的字符串

    然后字符串“null”中的每个字符都会被追加到缓冲区中

    注意:另一方面,new StringBuffer().append(null);会给你一个编译错误,因为重载的append()方法的参数null是不明确的,并且String.valueOf(null)会抛出一个Null Pointer Exception

  2. # 2 楼答案

    打印if条件内的缓冲区,并亲自查看:

    if(buffer.toString()!=null){
        System.out.println("Not NULL: " + buffer.toString());
    }
    

    输出:非空:空

    Null作为字符串存储在缓冲区中——作为“Null”而不是实际的Null

  3. # 3 楼答案

    以下是StringBuffer中toString()的实现

    public synchronized String toString() {
        return new String(value, 0, count);
        }
    

    可以看出,它总是调用new String(),因此将始终导致非null返回