Java 比较两个字符串的 == 是假的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/995918/
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 22:00:45  来源:igfitidea点击:

Java comparison with == of two strings is false?

javastringequals

提问by omg

String parts is String[6]:

字符串部分是字符串[6]:

["231", "CA-California", "Sacramento-155328", "aleee", "Customer Service Clerk", "Alegra Keith.doc.txt"]

But when I compare parts[0]with "231":

但是当我parts[0]"231"

"231" == parts[0]

the above result is false,

上面的结果是假的,

I'm confused, so could anybody tell me why?

我很困惑,所以有人能告诉我为什么吗?

回答by David Johnstone

==in Java compares the address of the objects (strings in this case).

==在 Java 中比较对象的地址(在这种情况下是字符串)。

What you want is parts[0].equals("231")

你想要的是 parts[0].equals("231")

回答by coobird

The ==operator compares the object references, not the value of the Strings.

==运营商比较对象引用,在不值String秒。

To compare the values of Strings, use the String.equalsmethod:

要比较Strings的值,请使用以下String.equals方法:

"231".equals(parts[0]);

This is true with any other object in Java -- when comparing values, always use the equalsmethod rather than using the ==operator.

Java 中的任何其他对象都是如此——在比较值时,始终使用equals方法而不是使用==运算符。

The equalsmethod is part of Object, and should be overridden by classes which will be compared in one way or another.

equals方法是 的一部分Object,应该被类覆盖,这些类将以一种或另一种方式进行比较。

回答by tputkonen

Use equals method: parts[0].equals("231"). == operator compares object references.

使用equals方法:parts[0].equals("231")。== 运算符比较对象引用。

回答by Yishai

If the strings are not interned, then == checks reference identity. Use:

如果字符串未实习,则 == 检查引用标识。用:

 "231".equals(parts[0]);

instead.

反而。

回答by basszero

"==" compares object references, in your case "231" is a different object than parts[0].

“==”比较对象引用,在您的情况下,“231”与parts[0] 是不同的对象。

You want to use String.equals.

您想使用String.equals

parts[0].equals("231")

回答by Malcolm

The answer is very simple: when you compare strings through == operator, you actually compare if two different variables refer to a single String object. And they don't, the string in the array and newly created "231" are different String objects with the same contents.

答案很简单:当您通过 == 运算符比较字符串时,您实际上是在比较两个不同的变量是否引用了单个 String 对象。而它们不是,数组中的字符串和新创建的“231”是具有相同内容的不同String对象。

The right thing to do is to use the folllowing expression: "231".equals(parts[0])or "231".equalsIgnoreCase(parts[0]). This will give you what you need and return true if these String objects contain the same values.

正确的做法是使用以下表达式:"231".equals(parts[0])or "231".equalsIgnoreCase(parts[0])。如果这些 String 对象包含相同的值,这将为您提供所需的内容并返回 true。

回答by Don Branson

Use the equals method to compare objects:

使用 equals 方法比较对象:

String[] test = {"231", "CA-California", "Sacramento-155328", "aleee",
                 "Customer Service Clerk", "Alegra Keith.doc.txt"};

System.out.println("231".equals(test[0]));

The comparison '==' compares references, not values.

比较 '==' 比较引用,而不是值。

回答by Carl Manaster

I thought it might be helpful to express the answer in a test case:

我认为在测试用例中表达答案可能会有所帮助:

public class String231Test extends TestCase {
    private String  a;
    private String  b;

    protected void setUp() throws Exception {
        a = "231";
        StringBuffer sb = new StringBuffer();
        sb.append("231");
        b = sb.toString();
    }

    public void testEquals() throws Exception {
        assertTrue(a.equals(b));
    }

    public void testIdentity() throws Exception {
        assertFalse(a == b);
    }
}

回答by Jesse

The following prints out "true";

以下打印出“true”;

String s = "231";
if(s == "231")
{
    System.out.println("true");
}
else
{
    System.out.println("false");
}

This is because Strings are not mutable and java will try and save as much space as possible, so it points both to the same memory reference.

这是因为字符串是不可变的,java 会尽量节省空间,所以它指向同一个内存引用。

However, the following prints out "false":

但是,以下打印出“false”:

String s = new String("231");
if(s == "231")
{
    System.out.println("true");
}
else
{
    System.out.println("false");
}

newwill force it to store the string in a new memory location.

new将强制它将字符串存储在新的内存位置。

By the way, you should ALWAYS use .equals()to compare strings (for cases just like this one)

顺便说一句,你应该总是.equals()用来比较字符串(对于这样的情况)

回答by Michael Zilbermann

As many others have already explained, you try to compare with equality operator, but then it would relies on Object.equals() instead of String.equals().

正如许多其他人已经解释过的那样,您尝试与相等运算符进行比较,但它会依赖于 Object.equals() 而不是 String.equals()。

So you can do the job by explicitly calling String.equals(), but instead of writing

所以你可以通过显式调用 String.equals() 来完成这项工作,而不是写

parts[0].equals("blahblah")

I would prefer such :

我更喜欢这样:

"blahblah".equals(parts[0])

As it avoids testing potential nullity of parts[0] (but be careful that parts variable itself could be null...)

因为它避免了测试部分 [0] 的潜在无效性(但要注意部分变量本身可能为空......)

Another way is using String.intern() :

另一种方法是使用 String.intern() :

if (parts[0].intern() == "blahblah") ...

See http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#intern()for more info on that.

有关更多信息,请参阅http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#intern()