字符串池与常量池 [英] String pool vs Constant pool

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

问题描述

让我们看一下以下代码片段:

Let's look at the folloing code snippet:

  String s1 = "Hello";
  String s2 = "Hello"; 

由于实习,两个变量都引用同一个对象。由于字符串是不可变的,因此只创建一个对象并且都引用同一个对象。

Both variables refer to the same object due to interning. Since strings are immutable, only one object is created and both refer to the same object.

A 常量池是还有一些东西,它包含在类中声明的所有常量(整数,字符串等)。它特定于每个类。

A constant pool is also something, which holds all the constants (integer, string, etc.) that are declared in a class. It is specific to each class.

 System.out.println("Hello");  // I believe this Hello is different from above.

问题:


  1. 字符串池是否引用常量池中常量字符串对象的池?

  2. 如果是, String pool 在整个应用程序中是通用的还是特定于类?

  1. Does string pool refer to the pool of a constant string object in the constant pool?
  2. If yes, is String pool common throughout the whole application or specific to a class?


推荐答案


我的问题是,

My questions are,


  1. 字符串池是指常量池常量池中的字符串对象?


否。

常量池是指类文件中特殊格式的字节集合,对Java类加载器有意义。其中的字符串是序列化,它们不是Java对象。还有很多种常量,而不仅仅是字符串。

"Constant pool" refers to a specially formatted collection of bytes in a class file that has meaning to the Java class loader. The "strings" in it are serialized, they are not Java objects. There are also many kinds of constants, not just strings in it.

参见第4.4章常量池表


Java虚拟机指令不依赖于类,接口,类实例或数组的运行时布局。相反,指令引用 constant_pool 表中的符号信息。

相比之下,字符串池在运行时使用(不仅仅在类加载期间),仅包含字符串,字符串池中的字符串是java对象。
字符串池是一个线程安全的弱映射,从 java.lang.String 实例到 java.lang.String 用于实习字符串的实例。

In contrast, the "String pool" is used at runtime (not just during class loading), contains only strings, and the "strings" in the string pool are java objects. The "string pool" is a thread-safe weak-map from java.lang.String instances to java.lang.String instances used to intern strings.

第3.10.5节。字符串文字


字符串文字是对类 String (§4.3.1,§4.3.3)。

A string literal is a reference to an instance of class String (§4.3.1, §4.3.3).

此外,字符串文字总是指相同的实例class String 。这是因为字符串文字 - 或者更常见的是作为常量表达式(第15.28节)的值的字符串 - 被实现以便使用方法 String.intern

Moreover, a string literal always refers to the same instance of class String. This is because 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.

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

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