Java中的字符串池是什么? [英] What is String pool in Java?

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

问题描述

我对 Java 中的 StringPool 感到困惑.我在阅读 Java 中的字符串章节时遇到了这个问题.请帮助我理解,通俗地说,StringPool 实际上是做什么的.

I am confused about StringPool in Java. I came across this while reading the String chapter in Java. Please help me understand, in layman terms, what StringPool actually does.

推荐答案

这会打印 true (即使我们不使用 equals 方法:比较字符串的正确方法)

This prints true (even though we don't use equals method: correct way to compare strings)

    String s = "a" + "bc";
    String t = "ab" + "c";
    System.out.println(s == t);

当编译器优化您的字符串文字时,它发现 st 具有相同的值,因此您只需要一个字符串对象.这是安全的,因为 String 在 Java 中是不可变的.
结果,st 都指向同一个对象,节省了一些内存.

When compiler optimizes your string literals, it sees that both s and t have same value and thus you need only one string object. It's safe because String is immutable in Java.
As result, both s and t point to the same object and some little memory saved.

名称字符串池"来自这样一个想法,即所有已定义的字符串都存储在某个池"中,并且在创建新的 String 对象之前,编译器会检查此类字符串是否已定义.

Name 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.

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

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