是什么让参考比较(==)适用于Java中的某些字符串? [英] What makes reference comparison (==) work for some strings in Java?

查看:128
本文介绍了是什么让参考比较(==)适用于Java中的某些字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码行来比较String。 str1不等于str2,这是可以理解的,因为它比较了对象引用。但那么为什么s1等于s2?

I have following lines of codes to compare String. str1 not equal to str2, which is understandable since it compares object reference. But then why s1 is equal to s2?

String s1 = "abc";
String s2 = "abc";

String str1 = new String("abc");
String str2 = new String("abc");

if (s1==s2)
    System.out.println("s1==s2");           
else
    System.out.println("s1!=s2");

if (str1==str2)
    System.out.println("str1==str2");           
else
    System.out.println("str1!=str2");

if (s1==str1)
    System.out.println("str1==s1");         
else
    System.out.println("str1!=s1");

输出:

  s1==s2
  str1!=str2
  str1!=s1 


推荐答案

字符串常量池本质上会缓存所有字符串文字,因此它们是下面的同一个对象,这就是为什么你看到你为 s1做的输出的原因== S2 。它本质上是VM中的一个优化,以避免每次声明文字时都创建一个新的字符串对象,这可能会非常快速地变得非常昂贵!使用 str1 == str2 示例,您明确告诉VM创建新的字符串对象,因此它是错误的。

The string constant pool will essentially cache all string literals so they're the same object underneath, which is why you see the output you do for s1==s2. It's essentially an optimisation in the VM to avoid creating a new string object each time a literal is declared, which could get very expensive very quickly! With your str1==str2 example, you're explicitly telling the VM to create new string objects, hence why it's false.

另外,在任何字符串上调用 intern()方法都会将其添加到常量池中(并返回它添加到池中的String。)这样做并不一定是个好主意,除非你确定你正在处理肯定会被用作常量的字符串,否则你最终可能难以追踪内存泄漏。

As an aside, calling the intern() method on any string will add it to the constant pool (and return the String that it's added to the pool.) It's not necessarily a good idea to do this however unless you're sure you're dealing with strings that will definitely be used as constants, otherwise you may end up creating hard to track down memory leaks.

这篇关于是什么让参考比较(==)适用于Java中的某些字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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