我读到声明为文字的字符串是在String Constant Pool String s1 = "Hello"; String s2 = "Hello"; ->上创建的,这不会创建新对象,而是引用s1引用。
并在堆内存和字符串常量池String s3 = new String("Hello"); ->上创建用new关键字声明的字符串,这将在堆中创建一个新对象。但是它是否也会在字符串常量池中创建一个新常量,还是会使用s1中的常量呢?
我有以下代码。所有s1、s2和s3哈希码都以相同方式返回。
public class question1 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1 == s3); // not sure why false result, s3 will create a separate constant in the pool? There is already a constant with value "Hello" created by s1. Please confirm if s3 will again create a constant.
}
}我理解==会比较对象。在字符串常数池中是否定义了两个"Hello“,一个来自s1,另一个来自s3?
发布于 2017-07-12 02:34:12
字符串文字会自动“内嵌”,这会将它们放入一个池中。这最大限度地减少了所需的实例数量。因此,这两个文字使用相同的String实例。hashCode()以一致的方式对字符串的内容进行操作。如果两个字符串实例具有相同的字符,则它们将具有相同的散列码。
https://stackoverflow.com/questions/45042020
复制相似问题