Equals method in java

I have read about a method equals()

in java. I heard that it only compares by value. But then why is it returning false for my case below, where the value is the same but the types are different?

public class test {
    public static void main(String[] args) 
    {
        String s1="compare";
        StringBuffer s2=new StringBuffer("compare");
        System.out.println(s1.equals(s2));  //false 
    }
}

      

+3


source to share


4 answers


A String

instance cannot be equal to an instance StringBuffer

.

Look at the implementation:



public boolean equals(Object anObject) {
if (this == anObject) {
    return true;
}
if (anObject instanceof String) { // this condition will be false in your case
    String anotherString = (String)anObject;
    int n = count;
    if (n == anotherString.count) {
    char v1[] = value;
    char v2[] = anotherString.value;
    int i = offset;
    int j = anotherString.offset;
    while (n-- != 0) {
        if (v1[i++] != v2[j++])
        return false;
    }
    return true;
    }
}
return false;
}

      

In theory, you can have an implementation equals

that can return true when comparing two objects of more than the same class (but not in a class String

), but I can't imagine a situation where such an implementation would make sense.

+11


source


String

different from StringBuffer

. Use toString()

to convert it to String

.



String s1="compare";
StringBuffer s2=new StringBuffer("compare");
System.out.println(s1.equals(s2.toString())); 

      

+3


source


Yes, Eran is right, you cannot match two different objects using equals. If you really want to do this, use toString()

in StringBuffer

System.out.println(s1.equals(s2.toString()));

      

0


source


The method equals()

belongs to Object

.

From Java docs for object

Indicates whether any other object is "equal" to this.

So basically:

The equals method for the Object class implements the most discriminatory object equivalence relation possible; that is, for any non-empty reference x and y, this method returns true if and only if x and y refer to the same object (x == y is true).

If you have String

and a StringBuffer

, they will not be equal to each other.

They may have the same meaning, but they are not equal, look at the method instanceOf()

.

0


source







All Articles