我知道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
中,有几种引用类型在某些时间间隔内对其值进行缓存(池)。此类类型例如:String
、Integer
(对于值 -128...127)。
所以,我想,你的 test2
类看起来像:
class test2 {
String a = "x" ;
}
或
class test2 {
Integer a = 1;
}
或类似的东西。
关于这些缓存,您可以阅读:
字符串
:What is the Java string pool and how is "s" different from new String("s")?
关于java - equals()方法和==相等还是不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25522783/