JDK 13 预览功能:文本块 returns false for equals and == 。制表符空格是否依赖?

JDK 13 preview feature :Textblock returns false for equals and == .Is the tab spaces dependent?

equals== return 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);
    }
}

我缺少什么?

让我们缩短 Strings。

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== 都应该 return true,尽管你不应该依赖后者。


阅读:

  1. Specification for JEP 355: Text Blocks (Preview)

相关: