• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
风吹花落泪如雨
博客园    首页    新随笔    联系   管理    订阅  订阅

Object:所有类的超类

Java中每个类都是由Object类扩展而来

1、equals方法

在Object类中,这个方法用于判断两个对象是否具有相同的引用,然而对于大多数类来说,经常需要检测两个对象状态的相等性。

public boolean equals(Object otherObject){
  if(this == otherObject)//检测this与otherObject是否引用同一个对象
     return true;
  if(otherObject == null)//检测otherObject是否为null
     return false;
  //在继承关系中的相等性测试,应该根据语义分两种情况考虑:
  //1.如果子类能够拥有自己的相等概念,则对称性需求将强制采用getClass进行检测。
  //2.如果由超类决定相等的概念,那么就可以使用instanceof进行检测,这样可以在不同子类的对象之间进行相等的比较。
  if(getClass() != otherObject.getClass())//比较this与otherObject是否属于同一个类。如果equals的语义在每个子类中有所改变,就使用getClass检测
     return false
  if(!(otherObject instanceof ClassName))//如果所有子类都拥有统一的语义,就使用instanceof检测
    return false;
  
  Employee other = (Employee) otherObject;
  return name.equals(other.name) && salary == other.salary;
}

为了防备name为null的情况,使用 Objects.equals方法。如果两个参数都为null,Objects.equals(a,b)返回true;如果一个参数为null,返回false;如果两个参数都不为null,调用a.equals(b)

return Objects.equals(name, other.name) && salary == other.salary;

在子类中定义equals方法时,首先调用父类的equals。只有相等时,才需要比较子类的实例域

public boolean equals(Object otherObject){
  if(!super.equals(otherObject))
    return false;
  Manager other = (Manager) otherObject;
  return bonus == other.bonus;
}

 

2、hashCode方法

散列码(hash code)是由对象导出的一个整型值。每个对象都有一个默认的散列码,其值为对象的存储地址。String的散列码是由内容导出的(覆盖hashCode方法)。

如果重新定义equals方法,就必须重新定义hashCode方法,以便用户可以将对象插入到散列表中。

public int hashCode(){
  return 7 * name.hashCode() + 11 * new Double(salary).hashCode() + 13 * hireDay.hashCode();

  return 7 * Objects.hashCode(name) + 11 * Double.hashCode(salary) + 13 * Objects.hashCode(hireDay);//null安全的方法Objects.hashCode。如果参数为null,返回0;否则返回对参数调用hashCode的结果

  return Objects.hash(name,salary,hireDay);//对各个参数调用Objects.hashCode,并组合这些散列值
}

Equals和hashCode的定义必须一致:如果x.equals(y)返回true,则x.hashCode()就必须与y.hashCode()具有相同的值

 

3、toString方法

只要对象与一个字符串通过操作符"+"连接起来,java编译就会自动地调用toString方法,以便获得这个对象的字符串描述

System.out.println(x);//println方法会直接调用x.toString()

 

posted @ 2018-07-10 01:09  风吹花落泪如雨  阅读(181)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3