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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/513832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:37:58  来源:igfitidea点击:

How do I compare strings in Java?

javastringequality

提问by Nathan H

I've been using the ==operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals()instead, and it fixed the bug.

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

Is ==bad? When should it and should it not be used? What's the difference?

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

采纳答案by Aaron Maenpaa

==tests for reference equality (whether they are the same object).

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

.equals()tests for value equality (whether they are logically "equal").

.equals()值相等的测试(它们在逻辑上是否“相等”)。

Objects.equals()checks for nullbefore calling .equals()so you don't have to (available as of JDK7, also available in Guava).

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

Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().

因此,如果您想测试两个字符串是否具有相同的值,您可能需要使用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

You almost alwayswant to use Objects.equals(). In the raresituation where you knowyou're dealing with internedstrings, you canuse ==.

您几乎总是想使用Objects.equals(). 在您知道要处理内部字符串的极少数情况下,您可以使用.==

From JLS 3.10.5. String Literals:

JLS 3.10.5。字符串文字

Moreover, a string literal always refers to the sameinstance 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.

此外,字符串字面量始终引用class的同一个实例String。这是因为字符串文字 - 或者更一般地说,作为常量表达式(第15.28 节)的值的字符串- 被“嵌入”,以便使用方法共享唯一实例String.intern

Similar examples can also be found in JLS 3.10.5-1.

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

Other Methods To Consider

其他需要考虑的方法

String.equalsIgnoreCase()value equality that ignores case.

String.equalsIgnoreCase()忽略大小写的值相等。

String.contentEquals()compares the content of the Stringwith the content of any CharSequence(available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.

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

回答by cletus

Yes, ==is bad for comparing Strings (any objects really, unless you know they're canonical). ==just compares object references. .equals()tests for equality. For Strings, often they'll be the same but as you've discovered, that's not guaranteed always.

是的,==不利于比较字符串(任何对象,除非你知道它们是规范的)。 ==只是比较对象引用。 .equals()测试是否相等。对于字符串,它们通常是相同的,但正如您发现的那样,并不能保证总是如此。

回答by coobird

==compares object references in Java, and that is no exception for Stringobjects.

==比较 Java 中的对象引用,对象也不例外String

For comparing the actual contents of objects (including String), one must use the equalsmethod.

为了比较对象(包括String)的实际内容,必须使用equals方法

If a comparison of two Stringobjects using ==turns out to be true, that is because the Stringobjects were interned, and the Java Virtual Machine is having multiple references point to the same instance of String. One should not expect that comparing one Stringobject containing the same contents as another Stringobject using ==to evaluate as true.

如果使用的两个String对象的比较==结果是true,那是因为这些String对象是实习的,并且 Java 虚拟机有多个引用指向 的同一个实例String。不应期望将String包含相同内容的一个String对象与另一个使用==评估为 的对象进行比较true

回答by Uri

Yea, it's bad...

是的,这很糟糕...

==means that your two string references are exactly the same object. You may have heard that this is the case because Java keeps sort of a literal table (which it does), but that is not always the case. Some strings are loaded in different ways, constructed from other strings, etc., so you must never assume that two identical strings are stored in the same location.

==意味着您的两个字符串引用是完全相同的对象。您可能听说过这种情况,因为 Java 保留了某种文字表(确实如此),但情况并非总是如此。某些字符串以不同的方式加载,由其他字符串等构造而成,因此您绝不能假设两个相同的字符串存储在同一位置。

Equals does the real comparison for you.

Equals 为您做了真正的比较。

回答by Matt Razza

.equals()compares the data in a class (assuming the function is implemented). ==compares pointer locations (location of the object in memory).

.equals()比较类中的数据(假设函数已实现)。 ==比较指针位置(对象在内存中的位置)。

==returns true if both objects (NOT TALKING ABOUT PRIMITIVES) point to the SAME object instance. .equals()returns true if the two objects contain the same data equals()Versus ==in Java

==如果两个对象(NOT TALKING ABOUT PRIMITIVES)都指向相同的对象实例,则返回 true。 .equals()如果两个对象包含相同的数据,则返回 trueequals()==Java 中的比较

That may help you.

那可能对你有帮助。

回答by Clayton

The ==operator checks to see if the two strings are exactly the same object.

==运营商检查是否两个字符串是完全相同的对象。

The .equals()method will check if the two strings have the same value.

.equals()方法将检查两个字符串是否具有相同的值。

回答by duffymo

String a = new String("foo");
String b = new String("foo");
System.out.println(a == b); // prints false
System.out.println(a.equals(b)); // prints true

Make sure you understand why. It's because the ==comparison only compares references; the equals()method does a character-by-character comparison of the contents.

确保你明白为什么。这是因为==比较只比较引用;该equals()方法对内容进行逐个字符的比较。

When you call new for aand b, each one gets a new reference that points to the "foo"in the string table. The references are different, but the content is the same.

当您为aand调用 new 时b,每个人都会获得一个指向"foo"字符串表中的新引用。参考文献不同,但内容相同。

回答by Whatsit

==tests object references, .equals()tests the string values.

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

Sometimes it looks as if ==compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object.

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

For example:

例如:

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";

But beware of nulls!

但要注意空值!

==handles nullstrings fine, but calling .equals()from a null string will cause an exception:

==处理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));

So if you know that fooString1may be null, tell the reader that by writing

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

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

The following are shorter, but it's less obvious that it checks for null:

以下较短,但它检查空值不太明显:

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

回答by pgras

I agree with the answer from zacherates.

我同意 zacherates 的回答。

But what you can do is to call intern()on your non-literal strings.

但是你可以做的是调用intern()你的非文字字符串。

From zacherates example:

从 zacherates 示例:

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

If you intern the non-literal String equality is true:

如果您实习,则非文字字符串相等性为true

new String("test").intern() == "test" ==> true 

回答by Faisal Feroz

Strings in Java are immutable. That means whenever you try to change/modify the string you get a new instance. You cannot change the original string. This has been done so that these string instances can be cached. A typical program contains a lot of string references and caching these instances can decrease the memory footprint and increase the performance of the program.

Java 中的字符串是不可变的。这意味着每当您尝试更改/修改字符串时,您都会获得一个新实例。您不能更改原始字符串。这样做是为了可以缓存这些字符串实例。一个典型的程序包含大量的字符串引用,缓存这些实例可以减少内存占用并提高程序的性能。

When using == operator for string comparison you are not comparing the contents of the string, but are actually comparing the memory address. If they are both equal it will return true and false otherwise. Whereas equals in string compares the string contents.

当使用 == 运算符进行字符串比较时,您不是在比较字符串的内容,而是在比较内存地址。如果它们都相等,则返回 true 和 false 否则。而字符串中的等于比较字符串内容。

So the question is if all the strings are cached in the system, how come ==returns false whereas equals return true? Well, this is possible. If you make a new string like String str = new String("Testing")you end up creating a new string in the cache even if the cache already contains a string having the same content. In short "MyString" == new String("MyString")will always return false.

所以问题是如果所有的字符串都缓存在系统中,为什么会==返回 false 而 equals 返回 true?嗯,这是可能的。如果您创建一个新字符串,就像String str = new String("Testing")您最终在缓存中创建一个新字符串一样,即使缓存已经包含具有相同内容的字符串。总之"MyString" == new String("MyString")总是会返回false。

Java also talks about the function intern() that can be used on a string to make it part of the cache so "MyString" == new String("MyString").intern()will return true.

Java 还讨论了可以在字符串上使用的函数 intern() 使其成为缓存的一部分,因此"MyString" == new String("MyString").intern()将返回 true。

Note: == operator is much faster than equals just because you are comparing two memory addresses, but you need to be sure that the code isn't creating new String instances in the code. Otherwise you will encounter bugs.

注意:== 运算符比 equals 快得多,因为您正在比较两个内存地址,但您需要确保代码没有在代码中创建新的 String 实例。否则你会遇到错误。