Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

Java .equals between String and StringBuilder

class returntest
{



public static void main(String...args)
{

String name1 = "Test";
String s = new String("Test");
StringBuilder sb = new StringBuilder("Test");

System.out.println(name1.equals(sb)); //Line 1
System.out.println(name1.equals(s));  //Line 2
System.out.println(s.equals(sb));     // Line 3
System.out.println(s.equals(name1));  //Line 4
}

}

The following is the output

false
true
false
true

Line 1 returns and Line 3 returns false.

I dont understand why compiler does not think "name1" and "sb" as containing the same value

Similarly compiler does not think "s" and "sb" as containing the same string (both are non-primitives).

Can someone explain the line1 and line3 output ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because they both are Different objects.

String object!= StringBuilder object.

But,Your doubt is

name1.equals(s)  returning true

Because in String class equals method ovverided in such a way.

And to get the desired output convert your StringBuilder to String.

System.out.println(s.equals(sb.toString())); //return true.

If you see the Source code of String#equals()

1012    public boolean  equals(Object anObject) {
1013        if (this == anObject) {
1014            return true;
1015        }
1016        if (anObject instanceof String) {             //key line 
1017            String anotherString = (String)anObject;
1018            int n = count;
1019            if (n == anotherString.count) {
1020                char v1[] = value;
1021                char v2[] = anotherString.value;
1022                int i = offset;
1023                int j = anotherString.offset;
1024                while (n-- != 0) {
1025                    if (v1[i++] != v2[j++])
1026                        return false;
1027                }
1028                return true;
1029            }
1030        }
1031        return false;
1032    }

The line if (anObject instanceof String) { always returns false incase if you pass StringBuilder.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...