java - 如何比较 Java 中的字符串?

标签 java string equality

这个问题的答案是 community effort .编辑现有答案以改进这篇文章。它目前不接受新的答案或交互。








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

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

最佳答案

==测试引用相等性(它们是否是同一个对象)。.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() .在 稀有 你的情况了解你正在处理interned字符串,您可以使用 == .
来自 JLS 3.10.5. String Literals :

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.


类似的例子也可以在 JLS 3.10.5-1 中找到。 .
其他需要考虑的方法
String.equalsIgnoreCase()忽略大小写的值相等。但是请注意,这种方法在各种与语言环境相关的情况下可能会产生意想不到的结果,请参阅 this question .
String.contentEquals()比较 String 的内容任何 CharSequence 的内容(从 Java 1.5 开始可用)。使您不必在进行相等比较之前将您的 StringBuffer 等转换为字符串,但将空值检查留给您。

关于java - 如何比较 Java 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41221879/

相关文章:

java - 在 NamedParameterJdbcTemplate 类型中不适用于参数 (String, new RowMapper<User>(){})

nullpointerexception - 什么情况下会得到NullPointerException ("Name is null");错误?

c# - 分割字符串“a_b_c_d.1.2.3.4”的更好方法

ruby - 如何测试哈希的顺序意识相等性

java - JPA Hibernate 一对一关系

java - 绘制动态图。

arrays - 为什么两个相同的字符串变量不相等?是因为字节数组大小吗?

Javascript - 使用变量作为连接字符串访问对象节点

c# mvvm IEqualityComparer with IChangeTracking

java - 将原始对象与包装对象进行比较,== 行为无法解释