有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java比较空对象

我有一个问题 我有两个空对象,我使用equals()方法来比较它们,因为我们知道equals方法比较对象的内容,但在这种情况下,我的对象没有任何属性

   Object ob1 = new Object();
   Object ob2 = new Object();
    if(ob1.equals(ob2)){
        System.out.println(" they are Equal");
    }
    else{ 
        System.out.println("not equal");
    }
    if(ob1 == ob2){
        System.out.println(" they are Equal");
    }
    else{ 
        System.out.println("not equal");
    } 

我们知道==将比较对象的引用

equals方法在这里比较什么

先谢谢你


共 (5) 个答案

  1. # 1 楼答案

    虽然关于X.equals(Y)的含义(即它应该回答什么“问题”)存在一些不一致之处,但有两个有用的问题:

    • 当对象按预期使用时,是否应该将对X的某些引用替换为对Y的引用而不会改变它们的行为

    • 当对象按预期使用时,将X的所有引用与对Y的引用进行交换,反之亦然是否不会改变它们的行为

    如果Object定义hashCode()为所有空对象返回相同的值,并且equals在比较任何两个空对象时返回true,则这些定义将满足#1。另一方面,任何定义equals以测试引用相等性和hashCode以返回identityHashCode的对象也将满足#1(如果XY是不同的实例,那么X.equals(X)是真的,但Y.equals(X)本身就是将对象视为不同的好理由

    尽管Object是否应该是一种具体类型仍有争议,但仅使用Object实例作为身份标记。因此,Object是一个具体类型的事实意味着它的equals方法应该测试身份

  2. # 2 楼答案

    Object.equalsJavaDoc:

    类对象的equals方法在对象上实现了最有区别的等价关系;也就是说,对于任何非空引用值x和y,当且仅当x和y引用同一对象(x==y的值为true)时,此方法才返回true

  3. # 3 楼答案

    它还将比较引用,如here所述:

    The equals method implements an equivalence relation on non-null object references:

    It is reflexive: for any non-null reference value x, x.equals(x) should return true.
    It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
    It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
    It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
    For any non-null reference value x, x.equals(null) should return false.

  4. # 4 楼答案

    1. == operator compare reference or memory location of objects in heap, whether they point to same location or not.

    2. equals() method main purpose is two compare the state of two objects or contents of the object.

    但是您正在使用Objectclassequals()方法

    Object class default implementation of equals() method work like == ,means it will check the memory reference of the object if they point to same location.

    注: 此默认实现被重写,以便在诸如字符串、包装器类之类的类中进行内容比较

  5. # 5 楼答案

    如果两个对象都是null,那么

     if(ob1==null && ob2==null)
    

    如果你尝试做ob1.equals(null),你会得到NullPointerException。自ob1以来,它自身null