简体   繁体   English

等于java中的方法

[英]equals method in java

I have read about the equals() method in java. 我已经阅读了java中的equals()方法。 I've heard that it compares based just on value. 我听说它仅基于价值进行比较。 But then why is it returning false for my case below where the value is the same but the types are different? 但是为什么它会在下面的情况下返回false,其中值相同但类型不同?

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

A String instance cannot be equal to a StringBuffer instance. String实例不能等于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 equals implementation that may return true when comparing two objects not of the same class (not in the String class though), but I can't think of a situation where such an implementation would make sense. 从理论上讲,你可以有一个equals实现,在比较不同类的两个对象时可能会返回true(虽然不在String类中),但是我想不出这种实现有意义的情况。

String is different from StringBuffer . StringStringBuffer不同。 Use toString() to convert it to a String . 使用toString()将其转换为String

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

Yes Eran is right you can't compair two diffrent objects using equals . 是的Eran是对的,你不能使用equals来计算两个不同的对象。 If you really wants to do that then use toString() on StringBuffer 如果你真的想这样做,那么在StringBuffer上使用toString()

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

The equals() method belongs to Object . equals()方法属于Object

From the Java docs for Object 来自Java文档的Object

Indicates whether some other object is "equal to" this one. 指示某个其他对象是否“等于”此对象。

So basically: 所以基本上:

The equals method for class Object implements the most discriminating possible equivalence relation on objects; 类Object的equals方法实现了对象上最具辨别力的等价关系; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). 也就是说,对于任何非空引用值x和y,当且仅当x和y引用同一对象时,此方法才返回true(x == y的值为true)。

If you have a String and a StringBuffer they would not be equal to each other. 如果你有一个String和一个StringBuffer它们就不会彼此相等。

They might have the same value, but they aren't equal, have a look at the instanceOf() method. 它们可能具有相同的值,但它们不相等,请查看instanceOf()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM