gpt4 book ai didi

java - java中比较内存池中已经存在的字符串

转载 作者:行者123 更新时间:2023-12-02 03:03:14 29 4
gpt4 key购买 nike

所以我读过,如果你写这个:

String a="foo"; 
String b="foo";
System.out.println(a==b);

它将打印“true”,因为第一个实现检查内存池寻找“foo”,它找不到它,所以它创建一个新对象并将foo放入内存池,然后每个其他字符串将指向同一个对象。

如果你写:

String a="foo"; 
String b=new String("foo");
System.out.println(a==b);

它将打印“false”,因为您强制为 b 创建一个新对象,因此它不会从池中取出它。

我的问题是你是否这样写:

String a=new String("foo"); 
String b="foo";
System.out.println(a==b);

为什么它仍然打印“false”?我的意思是“a”创建了一个新对象并且不在内存池中查找,但是b应该在内存池中查找并找到创建的对象“a”并指向它。我在这里缺少什么?谢谢。

最佳答案

当您创建一个新对象时,它不在池中。

b should look in the memory pool and find the object "a" created and point to it.

它在池中,但它返回 "foo" 对象而不是 new String("foo") 对象,因此 == 是仍然是假的。

您可以使用 .intern() 将字符串放入池中,例如

String a = "food".substring(0, 3).intern();
String b = "foo";
assert a == b;

关于java - java中比较内存池中已经存在的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42156815/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com