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

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

问题描述

我对Java中的StringPool感到困惑。我在阅读Java中的String章节时遇到过这个问题。请以外行的方式帮助我理解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 (即使我们不使用等于方法:比较字符串的正确方法)

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);

当编译器优化你的字符串文字时,它会看到 s t 具有相同的值,因此您只需要一个字符串对象。它是安全的,因为 String 在Java中是不可变的。

结果, s t 指向同一个对象并保存了一些小内存。

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天全站免登陆