字符串池行为 [英] String Pool behavior

查看:203
本文介绍了字符串池行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了这篇有关Java字符串池的问题
并了解字符串池的基本概念但仍然不了解行为。

I read this Questions about Java's String pool and understand the basic concept of string pool but still don't understand the behavior.

首先:如果您直接指定值并且s1和s2都引用池中的同一对象,则它可以工作

First: it works if you directly assign the value and both s1 and s2 refer to the same object in the pool

String s1 = "a" + "bc";
String s2 = "ab" + "c";
System.out.println("s1 == s2? " + (s1 == s2));

但是如果我改变字符串s1 + =d,那么池应该有一个字符串对象A B C D?那么当我改变s2 + =d时,它应该在池中找到字符串对象abcd,并将对象分配给s2?但它没有,它们不会被引用到同一个对象。这是为什么?

But then if I change the string s1+="d", then the pool should have a string object "abcd"? then when I change the s2+="d", it should find the string object "abcd" in the pool and should assign the object to s2? but it doesn't and they aren't referred to the same object. WHY is that?

String s1 = "abc";
String s2 = "abc";
System.out.println("s1 == s2? " + (s1 == s2));

s1 += "d";                  
s2 += "d";
System.out.println("s1 == s2? " + (s1 == s2));


推荐答案

当您致电<$时,保证汇总字符串字符串上的c $ c> String.intern()。

String s1 = "abcd".intern();
String s2 = "abc";
s2 += "d";
s2 = s2.intern();
s1 == s2 // returns true

当编译器看到常量时,它足够智能优化并汇集字符串文字,即:

When compiler sees a constant it's smart enough to optimize and pool the string literal, i.e.:

String s1 = "abcd";
String s2 = "abcd";
s1 == s2 // returns true

Java语言规范声明:


每个字符串文字都是对一个实例(§4.3.1,§12.5)的引用
(§4.3)$ b $类String(§ 4.3.3)。 String
对象具有常量值。字符串
文字 - 或者更一般地说,字符串
是常量
表达式(第15.28节)的值 - 是实习所以
用于共享唯一实例,使用
方法String.intern。

Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.

因此,对于 s2 + =d,编译器并不像你那样聪明,只是汇集了d

So in the case of s2 += "d", compiler wasn't as clever as you are and just pooled "d".

这篇关于字符串池行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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