我如何在 Java 中比较字符串?

新手上路,请多包涵

到目前为止,我一直在我的程序中使用 == 运算符来比较我的所有字符串。但是,我遇到了一个错误,将其中一个更改为 .equals() 而它修复了错误。

== 坏了吗?什么时候应该使用,什么时候不应该使用?有什么不同?

原文由 Nathan H 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 503
2 个回答

== 测试引用相等性(它们是否是同一个对象)。

.equals() 测试值是否相等(它们是否包含相同的数据)。

Objects.equals() 在调用 --- null 之前检查 .equals() 所以你不必这样做(从 JDK7 开始可用,也可在 Guava 中使用)。

因此,如果您想测试两个字符串是否具有相同的值,您可能需要使用 Objects.equals()

 // These two have the same value
new String("test").equals("test") // --> true

// ... but they are not the same object
new String("test") == "test" // --> false

// ... neither are these
new String("test") == new String("test") // --> false

// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" // --> true

// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true

// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
Objects.equals(null, null) // --> true

您几乎 总是 想使用 Objects.equals() 。在 极少数 情况下,您 知道 自己正在处理驻留 字符串可以 使用 ==

来自 JLS 3.10.5。 字符串文字

此外,字符串文字总是指类的 同一个 实例 String 。这是因为字符串文字 - 或者更一般地说,作为常量表达式 ( §15.28 ) 值的字符串 - 是“内部的”以便共享唯一实例,使用方法 String.intern

类似的例子也可以在 JLS 3.10.5-1 中找到。

其他需要考虑的方法

忽略大小写的 String.equalsIgnoreCase() 值相等。但是请注意,此方法在各种与语言环境相关的情况下可能会产生意外结果,请参阅 此问题

String.contentEquals()String 的内容与任何 CharSequence 的内容进行比较(自 Java 1.5 起可用)。使您不必在进行相等比较之前将 StringBuffer 等转换为 String,但将空检查留给您。

原文由 Aaron Maenpaa 发布,翻译遵循 CC BY-SA 4.0 许可协议

== 测试对象引用, .equals() 测试字符串值。

有时它看起来好像 == 比较值,因为 Java 做了一些幕后工作以确保相同的内联字符串实际上是同一个对象。

例如:

 String fooString1 = new String("foo");
String fooString2 = new String("foo");

// Evaluates to false
fooString1 == fooString2;

// Evaluates to true
fooString1.equals(fooString2);

// Evaluates to true, because Java uses the same object
"bar" == "bar";

但要小心空值!

== 处理 null 字符串很好,但是从空字符串调用 .equals() 将导致异常:

 String nullString1 = null;
String nullString2 = null;

// Evaluates to true
System.out.print(nullString1 == nullString2);

// Throws a NullPointerException
System.out.print(nullString1.equals(nullString2));

因此,如果您知道 fooString1 可能为空,请通过写作告诉读者

System.out.print(fooString1 != null && fooString1.equals("bar"));

以下是较短的,但它检查 null 的情况不太明显:

 System.out.print("bar".equals(fooString1));  // "bar" is never null
System.out.print(Objects.equals(fooString1, "bar"));  // Java 7 required

原文由 Whatsit 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题