为什么JAVA中来自同一类的对象彼此不相等?
大家好,新年快乐
我是JAVA新手。我已经编写了如下代码。当我运行它时,我得到以下输出
1和2是相同的
1和2相等
为什么其他if语句不能获得相同的输出?所有3个对象(示例1、示例2和示例3)都派生自类“Test”。所有3个都来自同一来源,类别为“测试”。因此,不仅1vs 2,而且1vs 3和2vs 3应该相同/相等
有什么想法吗
我的代码在这里:
public class Test {
public static void main(String[] args) {
Test example1 = new Test();
Test example2 = example1;
Test example3=new Test();
if (example1==example2){
System.out.println("1 and 2 are same");
}
if (example1==example3){
System.out.println("1 and 3 are same");
}
if (example2==example3){
System.out.println("2 and 3 are same");
}
if (example1.equals(example2)){
System.out.println("1 and 2 are equal");
}
if (example1.equals(example3)){
System.out.println("1 and 3 are equal");
}
if (example2.equals(example3)){
System.out.println("2 and 3 are equal");
}
}
}
# 1 楼答案
==
在引用Java对象时计算指针相等性。您的两个指针example1和example2指向同一个对象,因此它们相等,而example1和example3指向不同的对象,因此它们不相等.equals()
默认情况下表现出相同的行为,并比较内存地址。您可以重写测试类中的方法,使其更智能地比较对象,但它所能做的只是运行==
。String是具有.equals()
自定义实现的类的示例