Java中所有类的超类Object

来源:互联网 发布:淘宝卖的红酒 编辑:程序博客网 时间:2024/05/19 13:25
  • Object的地位

在Java中所有的类都继承于Object类,但不用在声明一个类时显示的extends Object

Object中几个重要的方法:

1.equals方法:

用于检测一个对象是否等于另外一个对象,即判断两个对象是否具有相同的引用.然而对于大多数类来说这种检测没有太大意义。

在实际中用户更倾向与更具自己的标准来判断两个对象是否相等。例如:如果来年各个雇员的姓名 薪水和雇佣日期都一样,就认为他们是相等的。下买呢示例演示equals方法的实现

class Employee{   int salary;   String name;   String hireday;   //返回一个布尔值,true表示相等,否则不相等   @Override   public boolean equals(Object otherobject){   //如果是同一个引用则说明相等        if(this==otherobject) return true;   //参数不能为空        if(otherobject==null) return false;   //两个对象必须同属一个类(用到了反射)        if(this.getClass!=otherobject.getClass) return false;   //通过上买你的判断我们知道otherobject为一个非空的Employee对象   Employee other=(Employee)otherobject;   //接下来实现用户自己的比较标准:雇员的姓名 薪水和雇佣日期都一样   return    Object.equals(name,other.name)             &&salary==other.salary             &&Object.equals(hireday,other.hireday)     }}

如果存在继承关系,则先调用父类中的equals()方法,如果父类中的检测失败(对象不相等),就说明对象不可能相等。如果检测成功则在调用子类中的检测方法。例如:

class Manager extends Employee{   int bounds;   //返回一个布尔值,true表示相等,否则不相等   @Override   public boolean equals(Object otherobject){           if(!super.equals(otherobject)) return false;           Maanger other=(Maanger)otherobject;           return this.bounds==other.bounds;    }}

2.hashCode方法:

hash code又称为散列码,是由对象到处的一个整型值。不同的对象的散列码基本不会相同。

由于hashCode方法定义于Object类中,因此在用户没有重写此方法之前,每个对象都有一个默认的散列码,其值为对象的存储地址。
有一点需要注意:字符串的散列码是由内容导出的,String类重写了hashCode方法,如下:

class String{ @Override public int hashCode(){    int hash=0;    for(int i=0;i<length();i++){        hash=31*hash+charAt(i);      }    return hash;  } }

注意:

Equals与hashCode的定义必须一致:如果x.equals(y)返回true,那么x.hashCode()就必须与y.hashCode()具有相同的值。所以通常在上面的Employee类中加上:

@Overridepublic int hashCode(){  return Object.hash(name,salary,hireday);      }
0 0