Java字符串和StringPool [英] Java Strings and StringPool

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

问题描述

public String makinStrings() {
   String m = "Fred47";
   String s = "Fred";
   s = s + "47";
   s = s.substring(0);
   return s.toString();
} 

代码创建了多少个对象?

How many objects are created by the code?

我做了一个简单的测试:

I made a simple test:

public static void main(String[] args) {
   String m = "a";
   m += "bc";
   String s1 = "mabc".substring(1);
   String s2 = "abc";

   System.out.println(m == "abc");
   System.out.println(m == s1);
   System.out.println(m == s2);
   System.out.println(s1 == s2);
}

结果不应该是真,真,真,真,如果m,s1,s2指向同一个对象(abc)?
而不是结果是假,假,假,假!

Shouldn't the result be "true, true, true, true", if m, s1, s2 point to the same object ("abc")? Instead the result is "false, false, false, false"!

推荐答案

结果在这种情况下是真的 - 但 m s1 s2 都引用不同的字符串。对于常量字符串表达式自动执行Interning,可以通过调用 实习生 方法,但字符串连接和子字符串不会自动发生。

The result would be true in that case - but m, s1 and s2 all refer to different strings. Interning is performed automatically for constant string expressions, and can be explicitly invoked by calling the intern method, but it doesn't happen for string concatenation and substrings automatically.

在Sun的Java 7实现中, x.substring(0) 实际返回相同的引用( x )又回来了,但我不相信API会保证这一点。

In Sun's Java 7 implementation, x.substring(0) will actually return the same reference (x) back again, but I don't believe that's guaranteed by the API.

看看你的例子:

public String makinStrings() {
   String m = "Fred47";
   String s = "Fred";
   s = s + "47";
   s = s.substring(0);
   return s.toString();
}

前两行要求内存中有两个字符串,但我不知道不知道什么时候可以保证创建对象。一旦他们创建,他们就会坚持下去 - 所以再次调用 makinStrings 将不再在这两行中创建。

The first two lines require that there are two strings in memory, but I don't know exactly when it's guaranteed that the objects are created. Once they have been created, they will stick around - so calling makinStrings again won't create any more in those two lines.

字符串连接创建一个新的字符串对象。

The string concatenation will create a new string object.

substring call 不会在我看过的实现中创建一个新的字符串对象 - 但它可以。

The substring call won't create a new string object in the implementation I've looked at - but it could.

s.toString() 的调用将不会创建一个新字符串(这在JavaDoc中指定)。

The call to s.toString() won't create a new string (and this is specified in the JavaDoc).

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

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