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

标签 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"; } 

最佳答案

看起来像画谜,但没什么奇怪的。在java中,有几种引用类型在某些时间间隔内对其值进行缓存(池)。此类类型例如:StringInteger(对于值 -128...127)。

所以,我想,你的 test2 类看起来像:

class test2 {
    String a = "x" ;
}

class test2 {
    Integer a = 1;
}

或类似的东西。

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

整数:Integers caching in Java

字符串:What is the Java string pool and how is "s" different from new String("s")?

关于java - equals()方法和==相等还是不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25522783/

相关文章:

java - 当我在 xml 文件中写入信息时 Eclipse 显示错误

java - 在运行时使用参数编写自定义 Kafka SSLEngineFactory

java - 在 oracle.jdbc.driver.T4CConnection 上找到锁定的对象

java - Gradle 子项目依赖项不起作用,但相同的依赖项在主 gradle 中工作正常

java8聚合对象转换器

java - Tomcat Maven 插件 - 子容器在启动期间失败

java - 从具有一位数小时偏移量的字符串中解析日期时间

java - 图表素面零线

java - 是否可以逐出spring缓存部分数据?

java - 具有相等元素的 JAX-B 枚举生成