java如何在底层实现字符串的享元模式? [英] How does java implement flyweight pattern for string under the hood?

查看:12
本文介绍了java如何在底层实现字符串的享元模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个 String 的两个实例,并且它们是相等的,那么在 Java 中它们将共享相同的内存.这是如何在幕后实施的?

If you have two instances of a String, and they are equal, in Java they will share the same memory. How is this implemented under the hood?

我的应用程序使用了大量 String 对象,其中许多是相同的.使用 Java String 常量池以避免创建自定义享元实现的最佳方法是什么?

My application uses a large number of String objects, many of which are identical. What is the best way to make use of Java String constant pool, as to avoid creating custom flyweight implementation?

推荐答案

查看java.lang.String的源码(整个java api的源码是JDK的一部分).

Look at the source code of java.lang.String (the source for entire java api is part of the JDK).

总结:一个字符串包装了一个char[]的子序列.支持 char[] 永远不会被修改.这是通过在 String 类之外既不泄漏也不捕获此 char[] 来实现的.但是,多个Strings 可以共享同一个char[](参见String.substring 的实现).

To summarize: A String wraps a subsequence of a char[]. That backing char[] is never modified. This is accomplished by neither leaking nor capturing this char[] outside the String class. However, several Strings can share the same char[] (see Implementation of String.substring).

还有实习机制,如其他答案中所述.

There is also the mechanism of interning, as explained in the other answers.

这篇关于java如何在底层实现字符串的享元模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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