Strange String pool behavior

后端 未结 4 1843
旧时难觅i
旧时难觅i 2021-01-30 10:02

I\'ve got a question of some strange String pool behavior. I\'m using == to compare equal Strings to find out whether they\'re in the pool or not.

p         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 10:32

    After decompiling this line

    System.out.println("555" == "555" + "");
    

    I got this bytecode

        LINENUMBER 8 L0
        GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
        ICONST_1
        INVOKEVIRTUAL java/io/PrintStream.println(Z)V
        ...
    

    which is equivalent to

      System.out.println(true);
    

    that means expression "555" == "555" + "" compiles to boolean true.

    For giveLiteralString() == giveLiteralString() + "" javac built this bytecode

        LINENUMBER 8 L0
        INVOKESTATIC Test1.giveLiteralString()Ljava/lang/String;
        NEW java/lang/StringBuilder
        DUP
        INVOKESTATIC Test1.giveLiteralString()Ljava/lang/String;
        INVOKESTATIC java/lang/String.valueOf(Ljava/lang/Object;)Ljava/lang/String;
        INVOKESPECIAL java/lang/StringBuilder.(Ljava/lang/String;)V
        INVOKEVIRTUAL java/lang/StringBuilder.toString()Ljava/lang/String;
        IF_ACMPNE L1
        ...
    

    which is equivalent to

    if (giveLiteralString() == new StringBuilder(giveLiteralString()).append("").toString()) {
    ...
    

    which will always produce false since here we're comparing 2 disctinct objects.

提交回复
热议问题