分配并创建新的字符串差异 [英] Assign and create new String difference

查看:99
本文介绍了分配并创建新的字符串差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        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之间的区别 s3
请让我知道

What is the difference between creation of s1 and s3 ? Please let me know

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

In String we are having only String object then why it treats this two differently. s1 and s2 are having different memory address while s3 and s4 has same memory address. why it works based on new operator.?

推荐答案

表示Java源代码中字符串文字的 String 对象被添加到共享 String 加载定义它们的类时的池。这确保了String文字的所有副本实际上都是同一个对象......即使文字出现在多个类中。这就是为什么 s3 == s4 true

The 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 loaded. 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 false 。 (这是 new 的基本属性。保证创建并返回一个新对象......如果它正常完成。)

By contrast, when you new a String, a distinct new String object is created. That is why s1 == s2 is false. (This is a fundamental property of new. It is guaranteed to create and return a new object ... if it completes normally.)

但是,在任何一种情况下,字符串都将具有相同的字符,这就是为什么等于返回 true

However, in either case, the strings will have the same characters, and that is why equals is returning true.

虽然理解正在发生的事情很重要,但真实教训是正确的比较Java字符串的方法是使用等于而不是 ==

While it is important to understand what is going on, the real lesson is that the correct way to compare Java strings is to use equals and not ==.

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

If you want to arrange that your String objects can be tested for equality using ==, you can "intern" them using the String.intern method. However, you have to do this consistently ... and interning is an expensive process in various respects ... so it is generally not a good idea.

这篇关于分配并创建新的字符串差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆