JDK 13预览功能:Textblock对于equals和==返回false。制表符是否依赖?

问题描述 投票:-2回答:1

[equals==返回文本块字符串的false,尽管它们在控制台中打印相同。

public class Example {
    public static void main(String[] args) {
        String jsonLiteral = ""
                + "{\n"
                + "\tgreeting: \"Hello\",\n"
                + "\taudience: \"World\",\n"
                + "\tpunctuation: \"!\"\n"
                + "}\n";

        String jsonBlock = """
                {
                    greeting: "Hello",
                    audience: "World",
                    punctuation: "!"
                }
                """;

        System.out.println(jsonLiteral.equals(jsonBlock)); //false
        System.out.println(jsonBlock == jsonLiteral);
    }
}

我想念的是什么?

java textblock java-13 preview-feature
1个回答
0
投票

让我们缩短String

String jsonLiteral = ""
        + "{\n"
        + "\tgreeting: \"Hello\"\n"
        + "}\n";

String jsonBlock = """
        {
            greeting: "Hello"
        }
        """;

让我们调试它们并打印其实际内容。

"{\n\tgreeting: \"Hello\"\n}\n"
"{\n    greeting: \"Hello\"\n}\n"

\t" "(四个ASCII SP字符或四个空格)不相等,整个String也不相等。您可能已经注意到,文本块中的缩进是由空格(不是水平制表符,换页符或任何其他类似空格的字符)形成的。

以下是the specification for JEP 355中的一些文本块示例:

String season = """
                winter""";    // the six characters w i n t e r

String period = """
                winter
                """;          // the seven characters w i n t e r LF

String greeting = 
    """
    Hi, "Bob"
    """;        // the ten characters H i , SP " B o b " LF

String salutation =
    """
    Hi,
     "Bob"
    """;        // the eleven characters H i , LF SP " B o b " LF

String empty = """
               """;      // the empty string (zero length)

String quote = """
               "
               """;      // the two characters " LF

String backslash = """
                   \\
                   """;  // the two characters \ LF

就您而言,

String jsonBlock = """
          {
              greeting: "Hello"
          }
          """; // the 26 characters { LF SP SP SP SP g r e e t i n g : SP " H e l l o " LF } LF

要使它们相等,请将"\t"替换为" "equals==都应返回true,尽管您不应该依赖后者。

© www.soinside.com 2019 - 2024. All rights reserved.