分配并创建新的字符串差异

2023-11-23

        String s1 = new String("string");
        String s2 = new String("string");

        String s3 = "string";
        String s4 = "string";

        System.out.println(s1 == s2);      //FALSE
        System.out.println(s2.equals(s1)); //TRUE

        System.out.println(s3 == s4);      //TRUE
        System.out.println(s3.equals(s4)); //TRUE

创建和创建有什么区别s1 and s3? 请告诉我

在 String 中,我们只有 String 对象,那么为什么它对这两个对象的处理方式不同。 s1 和 s2 具有不同的内存地址,而 s3 和 s4 具有相同的内存地址。 为什么它的工作原理基于new操作员。?


The String objects that represent string literals in your Java source code are added to a shared String pool when the classes that defines them are loaded1. This ensures that all "copies" of a String literal are actually the same object ... even if the literal appears in multiple classes. That is why s3 == s4 is true.

相比之下,当你new一个 String,创建一个不同的新 String 对象。因此s1 == s2 is false。 (这是一个基本属性new。如果正常完成,则保证创建并返回一个新对象。)

但是,无论哪种情况,字符串都将具有相同的字符,这就是为什么equals正在返回true.


虽然了解正在发生的事情很重要,real教训是correct比较 Java 字符串的方法是使用equals并不是==.

如果您想安排可以使用以下方法测试您的 String 对象的相等性==,你可以使用它们“实习”String.intern方法。然而,你必须始终如一地这样做……而且实习在各个方面都是一个昂贵的过程……所以这通常不是一个好主意。


1 - Actually, it is a bit more complicated than that. They objects get added to the pool at some time between class loading and first use of the literals. The precise timing is unspecified and JVM implementation dependent. However it is guaranteed to happen just once, and before any application code sees the String object reference corresponding to the literal.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

分配并创建新的字符串差异 的相关文章

随机推荐