为什么会出现这样的情况:如果我在两个包装器对象上运行.equals方法,它将按照下面的WrapperEqualsEquals类返回true,但是(并且我强调but)为什么我们需要在下面的Blob类中覆盖equals方法使其返回true。基本上,为什么包装器对象不得不重写.equals方法而逃脱了?

    class WrapperEqualsEquals
    {
       public static void main(String []args)
       {
         Integer one=new Integer(1);
         Integer oneB=new Integer(1);

         System.out.println(one == oneB);
         System.out.println(one.equals(oneB));

       }


        }

    class OverrideEquals
    {
      public static void main (String [] args)
      {
        Blob a= new Blob(1,"a");
        Blob b= new Blob(1,"a");



        System.out.println(a==b);
        System.out.println(a.equals(b));

       }


         }

    class Blob
    {
      int blobNumber;
      String blobText;

      Blob(int blobNumber,String blobText)
      {
       this.blobNumber=blobNumber;
       this.blobText=blobText;
      }

          //"overriding" the 'equals' method

          public boolean equals (Object o)
      {

            if (o instanceof Blob)
    {
        Blob o2=(Blob)o;
        return ((o2.blobNumber==this.blobNumber) &&(o2.blobText==this.blobText))?
                    true:false;
    }

            else
    {
        return false;
    }
}


}

最佳答案

默认情况下,仅当隐式和显式参数的哈希码相等时,Object#equals(Object)才返回true。因为您创建了两个单独的Blob对象,所以它们不会指向相同的引用(按照hashCode()),因此,除非覆盖.equals方法,否则它们将不相等。但是,按照Java约定,仅当两个对象的哈希码相等时,.equals才应返回true,因此您可能还希望覆盖hashCode。这还将保留内存使用情况。

07-28 02:22
查看更多