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

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);

    }

}

我缺少什么?


拉莫斯之舞
浏览 58回答 1
1回答

GCT1015

让我们把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 rString period = """                winter                """;          // the seven characters w i n t e r LFString greeting =     """    Hi, "Bob"    """;        // the ten characters H i , SP " B o b " LFString salutation =    """    Hi,     "Bob"    """;        // the eleven characters H i , LF SP " B o b " LFString empty = """               """;      // the empty string (zero length)String quote = """               "               """;      // the two characters " LFString 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,尽管您不应该依赖后者。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java