查看评论:
String str = "abcd"; // new String LITERAL which is interned in the pool String str1 = new String("abcd"); // new String, not interned: str1 != str String str2 = str.substring(0,2); // new String which is a view on str String str3 = str.substring(0,2); // same: str3 != str2 String str7 = str1.substring(0,str1.length()); // special case: str1 is returned笔记:
- 从Java 7u6开始,子字符串返回一个新字符串,而不是原始字符串的视图(但这在该示例中没有区别)
- 致电时的特殊情况
str1.substring(0,str1.length());
-请参见代码:
public String substring(int beginIndex, int endIndex) { //some exception checking then return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen); }编辑
什么是观点?
在Java 7u6之前,String基本上是a
char[],其中包含带有偏移量和计数的字符串
count字符(即,字符串由从中的
offset位置开始的字符组成
char[])。
调用子字符串时,将创建一个具有相同
char[]但不同的偏移量/计数的新字符串,以有效地在原始字符串上创建视图。(如上所述,当count =length和offset = 0时除外)。
由于Java 7u6,新
char[]创建的每个时间,因为没有更多的
count还是
offset外地的字符串类。
公用池到底存储在哪里?
这是特定于实现的。池的位置实际上已在最新版本中移动。在较新的版本中,它存储在堆中。
如何管理游泳池?
主要特征:
- 字符串文字存储在池中
- 实习字符串存储在池中(
new String("abc").intern();) - 当一个字符串
S
被拘留(因为它是文字还是因为intern()
被调用),JVM将参考返回一个字符串池中是否有一个是equals
到S
(因此"abc" == "abc"
应该总是返回true)。 - 可以对垃圾池中的字符串进行垃圾回收(这意味着如果某个被填充的字符串变满,可能会在某个阶段将其从池中删除)


![Java如何存储字符串以及子字符串在内部如何工作?[关闭] Java如何存储字符串以及子字符串在内部如何工作?[关闭]](http://www.mshxw.com/aiimages/31/391272.png)
