Java comparison with == of two strings is false? [duplicate]

被刻印的时光 ゝ 提交于 2019-11-25 23:22:51

问题


This question already has an answer here:

  • How do I compare strings in Java? 23 answers

String parts is String[6]:

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

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

\"231\" == parts[0]

the above result is false,

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


回答1:


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

To compare the values of Strings, use the String.equals method:

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

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

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




回答2:


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

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

instead.




回答3:


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

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




回答4:


The following prints out "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.

However, the following prints out "false":

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

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

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




回答5:


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




回答6:


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

You want to use String.equals.

parts[0].equals("231")



回答7:


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.

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.




回答8:


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);
    }
}



回答9:


You may also use compareTo(String) method:

String str = "test";

if( str.compareTo("test") == 0)
   //the argument string is equal to str;
else
   //the argument string is not equal to str;



回答10:


Use the equals method to compare objects:

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.




回答11:


Here's really nice example. The '==' operator with string can be really tricky in Java.

class Foo {
    public static void main(String[] args) {
        String a = "hello";
        String b = "hello";
        String c = "h";
        c = c + "ello";

        String operator = null;

        if(a == b) {
            operator = " == ";
        } else {
            operator = " != ";
        }

        System.out.println(a + operator + b);

        if(a == c) {
            operator = " == ";
        } else {
            operator = " != ";
        }

        System.out.println(a + operator + c);

        if(a == "hello") {
            operator = " == ";
        } else {
            operator = " != ";
        }

        System.out.println(a + operator + "hello");

        if(c == "hello") {
            operator = " == ";
        } else {
            operator = " != ";
        }

        System.out.println(c + operator + "hello");
    }
}

Which will produce following output:

hello == hello
hello != hello
hello == hello
hello != hello



回答12:


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().

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

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...)

Another way is using 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.



来源:https://stackoverflow.com/questions/995918/java-comparison-with-of-two-strings-is-false

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!