【发布时间】:2017-12-15 22:58:30
【问题描述】:
我读到声明为文字的字符串是在字符串常量池上创建的
String s1 = "Hello";
String s2 = "Hello"; -> 这不会创建新对象,而是引用 s1 引用。
在堆内存和字符串常量池上都创建了用 new 关键字声明的字符串
String s3 = new String("Hello"); -> 这将在堆中创建一个新对象。
但它会在字符串常量池中创建一个新常量还是使用 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?
【问题讨论】:
-
hashCode与引用相同无关。hashCode只关心.equals,而不关心==。s3根本不在常量池中。 -
==测试两个对象是否完全相同。new总是 创建一个新的、单独的对象。 -
把hashcode想象成你的生日,你和你的邻居可能是同一天出生,但你不是同一个人!
-
s3 将使用由 s1 创建的相同常量,还是会在池中创建一个单独的常量以及对象?