Java - 告诉String是否被实习? [英] Java - tell if a String is interned?

查看:128
本文介绍了Java - 告诉String是否被实习?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这里的问题非常简单:有没有办法判断Java中的 String 是否被实现?我的猜测是否定的,但我想知道是否有人知道更好。

So the question here is pretty simple: is there a way to tell if a String in Java is interned? My guess is no, but I'm wondering if anyone knows better.

推荐答案

唯一可以找出是否字符串被实习是要调用 intern()并检查它是否自行返回:

The only way you can find out if a String is interned is to call intern() and check if it returns itself:

boolean hasBeenInternedBefore = myString.intern() == myString;

这显然有实习 String 当它之前没有实习时。

This obviously has the drawback of interning the String when it wasn't interned before.

部分偏离主题,有一种方法可以使用 Interner Guava 的code>界面(使用 Interners class )。这样做的好处是能够让 Interner 本身(以及游戏池)在不再被引用时被垃圾收集。

Going partially off-topic, there's a way to do "custom" interning with an explicit pool using the Interner interface of Guava (using the implementations exposed by the Interners class). This has the advantage of being able to let the Interner itself (and thuse the pool) being garbage collected when it's no longer referenced.

这篇关于Java - 告诉String是否被实习?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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