关于Java的String pool的问题 [英] Questions about Java's String pool

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

问题描述

考虑这个代码:

String first = "abc"; 
String second = new String("abc");

当使用 new 关键字时,Java 会再次创建 abc String 对吧?这会存储在常规堆中还是 String 池中?有多少 String 会在 String 池中结束?

When using the new keyword, Java will create the abc String again right? Will this be stored on the regular heap or the String pool? How many Strings will end in the String pool?

推荐答案

如果使用 new 关键字,将创建一个新的 String 对象.请注意,对象始终在堆上——字符串池不是与堆分开的单独内存区域.

If you use the new keyword, a new String object will be created. Note that objects are always on the heap - the string pool is not a separate memory area that is separate from the heap.

字符串池就像一个缓存.如果你这样做:

The string pool is like a cache. If you do this:

String s = "abc";
String p = "abc";

那么 Java 编译器足够聪明,可以只生成一个 String 对象,并且 sp 都将引用同一个 String目的.如果你这样做:

then the Java compiler is smart enough to make just one String object, and s and p will both be referring to that same String object. If you do this:

String s = new String("abc");

那么池中就会有一个String对象,那个代表字面量的"abc",并且会有一个单独的String object,不在池中,它包含池对象内容的副本.由于 String 在 Java 中是不可变的,因此您不会通过这样做获得任何东西;调用 new String("literal") 在 Java 中毫无意义,而且效率低下.

then there will be one String object in the pool, the one that represents the literal "abc", and there will be a separate String object, not in the pool, that contains a copy of the content of the pooled object. Since String is immutable in Java, you're not gaining anything by doing this; calling new String("literal") never makes sense in Java and is unnecessarily inefficient.

请注意,您可以对 String 对象调用 intern().如果 String 对象不存在,这会将其放入池中,并返回对池化字符串的引用.(如果它已经在池中,它只返回对已经存在的对象的引用).有关详细信息,请参阅该方法的 API 文档.

Note that you can call intern() on a String object. This will put the String object in the pool if it is not already there, and return the reference to the pooled string. (If it was already in the pool, it just returns a reference to the object that was already there). See the API documentation for that method for more info.

另见字符串实习(维基百科).

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

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