java anotherstring_Can I use “==” to compare two String?(转)

引自:http://www.mengyan.org/blog/archives/2004/08/14/87.html

These days, when I’m reading some other guy’s code, I encounter some problem. In these code, I can read following codes:

JButtonbutton=newJButton("OK");

button.setActionCommand("OK");

button.addActionListener(this);

......

actionPerformed(e){

Strings=e.getActionCommand();

if(s=="OK")

......

}

Look, it use “==” but not “equals” here. “Oh, it must be a bug!”, I told myself. But, wait, when I excuted the program, it worked quite well. And till this moment, I remembered, current powerful JVM will maintain a constant pool for String, so maybe two “OK” will reference the same place. So, such mechanism will work.

But, does Java Language Specification has such standard? and all JVM will follow this standard? I continue to dig into it.

First, I found such item in JLS 3.10.5 — String literals.

Abstract some points here:Literal strings within the same class ($8) in the same package ($7) represent references to the same String object ($4.3.1).

Literal strings within different classes in the same package represent references to the same String object.

Literal strings within different classes in different packages likewise represent references to the same String object.

Strings computed by constant expressions ($15.28) are computed at compile time and then treated as if they were literals.

Strings computed at run time are newly created and therefore distinct.

The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.

So, this is the feature of String class, every JVM should follow. And, when I read the code of String.java, I found such comments in method “intern“.public String intern()

Returns a canonical representation for the string object.

A pool of strings, initially empty, is maintained privately by the class String.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~So good:-)

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned. String literals are defined in $3.10.5 of the Java Language Specification.

It’s quite clear about the case I encountered. Then I understand, this is not a bug, but the trick

icon_razz.gif . But, why he use “==” but not “equals“, I think that will be more clear and more easy to read, I think there must be other guys to be puzzled as me

icon_smile.gif .

I think the author must care more about the performance than the code, the performance of “==” sure if better than “equals“, especially when the String is long~.

Ok, everything clear now, and sure, not only String has such pool. For example:

Integeri=1;

Integerj=1;

what will System.out.println(i==l) output? I think you can get the right answer.

icon_razz.gif

Update (2005.11.09):

"String"’s method "equalsIgnoreCase" also take advantage of this string pool:

publicbooleanequalsIgnoreCase(StringanotherString){

return(this==anotherString)?true:

(anotherString!=null)&&(anotherString.count==count)&&

regionMatches(true,0,anotherString,0,count);

}

If the two string point the same one, simply return true.

So, if you need to compare Strings frequently, you should "Intern" them.

For example, in Lucene’s source code, you need to compare the Field name very often, so, they intern the field name.

this.name=name.intern();// field names are interned

Popularity: 9%

This entry was posted on Saturday, August 14th, 2004 at 5:25 pm and is filed under 技术. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java String 类型 API 测试代码 1.String和char[]之间的换 toCharArray(); 2.String和byte[]之间的换 getBytes() Arrays工具类 : Arrays.toString(names) StringString replace(char oldChar, char newChar) String replace(CharSequence target, CharSequence replacement) String[] split(String regex) boolean contains(CharSequence s):当且仅当此字符串包含指定的 char 值序列时,返回 true int indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引 int indexOf(String str, int fromIndex):返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始 int lastIndexOf(String str):返回指定子字符串在此字符串中最右边出现处的索引 int lastIndexOf(String str, int fromIndex):返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索 boolean endsWith(String suffix):测试此字符串是否以指定的后缀结束 boolean startsWith(String prefix):测试此字符串是否以指定的前缀开始 boolean startsWith(String prefix, int toffset):测试此字符串从指定索引开始的子字符串是否以指定前缀开始 int length():返回字符串的长度: return value.length char charAt(int index): 返回某索引处的字符return value[index] boolean isEmpty():判断是否是空字符串:return value.length == 0 String toLowerCase():使用默认语言环境,将 String 中的所有字符换为小写 String toUpperCase():使用默认语言环境,将 String 中的所有字符换为大写 String trim():返回字符串的副本,忽略前导空白和尾部空白 boolean equals(Object obj):比较字符串的内容是否相同 boolean equalsIgnoreCase(String anotherString):与equals方法类似,忽略大小写 String concat(String str):将指定字符串连接到此字符串的结尾。 等价于用“+” String substring(int beginIndex):返回一个新的字符串,它是此字符串的从beginIndex开始截取到最后的一个子字符串。 String substring(int beginIndex, int endIndex) :返回一个新字符串,它是此字符串从beginIndex开始截取到endIndex(不包含)的一个子字符串。
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值