java中重写equals方法

本文深入探讨了Java中Cat类的equals和hashCode方法的正确实现方式,确保对象间的比较遵循自反性、对称性和传递性的原则,并通过示例展示了这些方法的实际效果。

import java.util.Date;

class Dog{


 private String name;
 private Date birthday;
 
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Date getBirthday() {
  return birthday;
 }
 public void setBirthday(Date birthday) {
   this.birthday = birthday;
 }
 
 
}


public class Cat {

 /**Cat类中含有name和birthday两私有成员变量,且重写了equals方法和hashCode方法
  *
  * @param name 和 birthday
  *
  */
 
 private String name;
 private Date birthday;
 
 public Cat(){}
 
 
 
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public Date getBirthday() {
  return birthday;
 }

 public void setBirthday(Date birthday) {
  this.birthday = birthday;
 }
 
 /*
  * 重写equals必须注意:
  *   1 自反性:对于任意的引用值x,x.equals(x)一定为true
  *   2  对称性:对于任意的引用值x 和 y,当x.equals(y)返回true,y.equals(x)也一定返回true
  *   3 传递性:对于任意的引用值x、y和z,如果x.equals(y)返回true,并且y.equals(z)也返回true,那么x.equals(z)也一定返   回 true
   * 4 一致性:对于任意的引用值x 和 y,如果用于equals比较的对象信息没有被修改,
   *           多次调用x.equals(y)要么一致地返回true,要么一致地返回false
   *   5 非空性:对于任意的非空引用值x,x.equals(null)一定返回false
   * 
   * 请注意:
   * 重写equals方法后最好重写hashCode方法,否则两个等价对象可能得到不同的hashCode,这在集合框架中使用可能产生严重后果
  */
 
 
 /*
  *  1.重写equals方法修饰符必须是public,因为是重写的Object的方法.
     *  2.参数类型必须是Object.
  */
 public boolean equals(Object other){       //重写equals方法,后面最好重写hashCode方法
 
  if(this == other)                                      //先检查是否其自反性,后比较other是否为空。这样效率高
   return true;
  if(other == null)        
   return false;
  if( !(other instanceof Cat))
   return false;
 
  final Cat cat = (Cat)other;
 
  if( !getName().equals(cat.getName()))
   return false;
  if( !getBirthday().equals(cat.getBirthday()))
   return false;
  return true;
 }
 
 public int hashCode(){                 //hashCode主要是用来提高hash系统的查询效率。当hashCode中不进行任何操作时,可以直接让其返回 一常数,或者不进行重写。
  int result = getName().hashCode();
  result = 29 * result +getBirthday().hashCode();
  return result;
  //return 0;
 }

 public static void main(String[] args) { 
 
  Date dayA = new Date(4000000); 
  Cat a = new Cat();
  a.setName("a");
  a.setBirthday(dayA);
 
  Date dayB = new Date(1000000);
  Cat b = new Cat();
  b.setName("a");
  b.setBirthday(dayB);
 
  Date dayC = dayA;
  Cat c = new Cat();
  c.setName("a");
  c.setBirthday(dayC);
 
  Date dayE = dayA;
  Cat e = new Cat();
  e.setName(a.getName());
  e.setBirthday(a.getBirthday());
 
  Date dayD = dayC;
  Dog d = new Dog();
  d.setName("a");
  d.setBirthday(dayD);
 
  System.out.println(a.equals(b));     //调用自己类中所定义的equals方法
  System.out.println(a.equals(a));
  System.out.println(a.equals(c));
 
  System.out.println(d.equals(a));
  System.out.println(a.equals(d));      //验证重写equals的对称性
  System.out.println(a.equals(e));
  System.out.println(e.equals(c));      //验证重写equals的传递性
  System.out.println(d.getName().equals(a.getName()));   //调用Object类中equals方法
  System.out.println(d.getBirthday().equals(b.getBirthday()));
 
  System.out.println("比较hanshCode的值");
 
  /*
   *    * 比较hashCode方法中返回的值
   * 如果equals返回为true,则hashCode一定返回true。
   * 如果equals返回为false,hashCode返回值不一定不相同。
   * 如果hashCode返回值不同,则equals返回值一定为false。
   * 如果hashCode返回值不同,则equals返回值不一定为false。
   */
  System.out.println(a.hashCode());
  System.out.println(b.hashCode());
  System.out.println(a.hashCode()== b.hashCode());    //如果equals返回false,则各hashCode不一定返回不同值
  System.out.println(a.hashCode() == c.hashCode());   
       
 }

}

Java 中,默认的 `equals` 方法比较的是两个对象的地址值,若要实现按内容对比对象是否相同,就需要重写 `equals` 方法。 以下是重写 `equals` 方法的通用步骤和示例: 1. **检查引用是否相同**:先判断两个引用是否指向同一个对象,如果是则直接返回 `true`。 2. **检查对象是否为 `null`**:若传入的对象为 `null`,则返回 `false`。 3. **检查对象类型**:判断传入的对象是否为当前类的实例,若不是则返回 `false`。 4. **类型转换**:将传入的对象转换为当前类的类型。 5. **比较对象属性**:逐一比较对象的属性是否相等。 以下是几个具体的示例: #### 示例 1:`Person` 类 ```java public class Person { private String id; private String name; public Person() {} public Person(String id, String name) { this.id = id; this.name = name; } @Override public boolean equals(Object obj) { // 如果引用指向的为同一个对象,则返回 true if (this == obj) { return true; } // 当引用指向的为不同的对象的时候,判断对象属性是否相等 if (obj != null && obj.getClass() == Person.class) { Person personObj = (Person) obj; if (personObj.getId().equals(this.getId()) && personObj.getName().equals(this.getName())) { return true; } } return false; } //================getter and setter=============================== public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` #### 示例 2:`Data` 类 ```java class Data { int year; int month; int day; Data(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public boolean equals(Object x) { if (this == x) return true; if (x == null) return false; // 能调用这个方法,this 肯定不为 null,所以不判断 this if (this.getClass() != x.getClass()) return false; // 如果不是同一个类,则必然 false Data that = (Data) x; // 将 Object 类型的 x 转换为 Data 型。因为上一行已经判断了 x 是否为 Data 型,所以可以直接转换 if (this.year != that.year) return false; if (this.month != that.month) return false; if (this.day != that.day) return false; return true; } } ``` 通过上述示例可以看出,重写 `equals` 方法的核心是对对象的属性进行逐一比较,以确保对象内容的一致性。 [^3][^4]
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值