为了账号安全,请及时绑定邮箱和手机立即绑定

JDK 13 预览功能:Textblock 对于 equals 和 == 返回 false。

JDK 13 预览功能:Textblock 对于 equals 和 == 返回 false。

拉莫斯之舞 2023-09-06 15:39:55
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);    }}我缺少什么?
查看完整描述

1 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

让我们把Strings 改短一些。


String jsonLiteral = ""

        + "{\n"

        + "\tgreeting: \"Hello\"\n"

        + "}\n";


String jsonBlock = """

        {

            greeting: "Hello"

        }

        """;

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


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

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

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

以下是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,尽管您不应该依赖后者。

查看完整回答
反对 回复 2023-09-06
  • 1 回答
  • 0 关注
  • 57 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信