gpt4 book ai didi

java - java中字符串是如何处理的

转载 作者:搜寻专家 更新时间:2023-10-31 19:32:42 25 4
gpt4 key购买 nike

String a = "abc";

这会在字符串池中创建文字 "abc"

String b = "abc";

没有创建新的文字。 b 指向已有的"abc"

String c = new String("abc");

现在对象在堆中创建,c 指向堆。文字也在字符串池中创建。

但是,如果池中已经有文字 "abc" 会怎样?池中会不会有重复字面量?

最佳答案

But, what happens if the pool already has the literal "abc"? Will there be duplicate literals in the pool?

没有。

String c = new String("abc");

在语义上等同于

String tmp = "abc";
String c = new String(tmp);

由此应该清楚,字符串池中没有额外的条目被创建只是因为文字被用作字符串构造函数的参数。

new String(...) 在堆上创建了一个字符串,你是对的,所以查看堆和字符串池,将有多个对象表示 "abc",但在字符串池中不超过一个。

[...] That is when we use string literals. But will the literal in the string pool be reused if we give, String a = new String("abc");?

是的,如果您将“abc”作为构造函数的参数,字符串池文字将被重用。然而,生成的 String 对象不会在池中,而是在堆中。

关于java - java中字符串是如何处理的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30843231/

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