gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:27:37 25 4
gpt4 key购买 nike

我知道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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com