Java中String.intern函数的用途

本文详细介绍了 Java 中 java.lang.String 类的 intern() 方法的工作原理。通过内部化字符串可以确保所有相同的字符串引用都指向同一个实例,从而允许使用 == 运算符进行比较,而不是通常所需的 equals() 方法。此外,文章还探讨了使用 intern() 方法的优势和潜在缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

First off, let's make sure that we all understand what java.lang.String.intern() actually does... Basically, it internalizes strings such that for any two strings, s1.intern() == s2.intern() if and only if s1.equals(s2). In other words, it makes sure that the returned string reference points to the single, canonical version of that string of characters. It does this by managing a pool of unique string values.


Now, as noted in What are the differences between the == operator and the equals() method?, we know that, typically, we can't use the == operator to compare string values because the == operator is just comparing the values of references to those strings rather than the strings' values. But, for internalized strings, since we know that the value of the reference will always be to the unique, canonical version of the string, we can use the == operator.


Therefore, the primary benefit in this case is that using the == operator for internalized strings is a lot faster than use the equals() method. So, use the intern() method if you're going to be comparing strings more than a time or three.


The primary disadvantage is that you have to remember to make sure that you actually do intern() all of the strings that you're going to compare. [Note that you don't have to intern() string literals or string-valued constants.] It's easy to forget to intern() all strings and then you can get confusingly incorrect results. Also, for everyone's sake, please be sure to very clearly document that you're relying on the strings being internalized.


The second disadvantage if you decide to internalize strings is that the intern() method is relatively expensive. It has to manage the pool of unique strings so it does a fair bit of work (even if the string has already been internalized). So, be careful in your code design so that you e.g., intern() all appropriate strings on input so you don't have to worry about it anymore.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值