equals()方法和==是相等还是不相等?

时间:2014-08-27 08:50:34

标签: java

我知道Object.equals()比较堆内存中对象的值。和==比较参考文献。

但是当我运行我的代码时,我两者都是平等的。

public class test3 {
    public static void main(String args[]){
        test2 ts = new test2();
        test2 tss = new test2();

        if(ts.a == tss.a){
            System.out.println("they are equal");
        }else
            System.out.println("they are unequal..");

        if(ts.a.equals(tss.a)){
            System.out.println("equal");
        }else
            System.out.println("not equal..");
    }
}

public class test2 { String a= "soumya"; } 

3 个答案:

答案 0 :(得分:3)

看起来像是一种叛逆,但没有什么令人惊讶的。在java中,有几种引用类型在某些时间间隔内具有其值的缓存(池)。这些类型例如:StringInteger(对于值-128 ... 127)。

所以,我想,你的test2课程看起来像是:

class test2 {
    String a = "x" ;
}

class test2 {
    Integer a = 1;
}

或类似的东西。

关于这些缓存,您可以阅读:

IntegerIntegers caching in Java

StringWhat is the Java string pool and how is "s" different from new String("s")?

答案 1 :(得分:1)

由于您使用类test2的定义更新了您的问题,现在答案很明确:使用intern()将字符串的常量存储到内部缓存中。

这一部分:

  

所有文字字符串和字符串值常量表达式都是   实习即可。字符串文字在Java语言的§3.10.5中定义   说明书

这就是为什么引用和相等(使用equals)同时返回true

答案 2 :(得分:0)

大多数情况下,==(默认为Object#equals(Object o))返回与equals()相同

请在源代码中查看equals(Object obj)的{​​{1}}:

Object

当且仅当它们的引用是同一个时,它们才返回true。

但有时,如果equals()已被覆盖,它们可能不一样。最常见的情况是public boolean equals(Object obj) { return (this == obj); } 已覆盖String来制作只要s1和s2具有相同的字面值,s1.equals(s2)就返回true。

请检查以下输出:

equals()
相关问题