关于Object类的equals方法

equals方法只通过判断两个变量是否指向同一块内存区域来判断相等,

  students[0] = new Student("怀化学院", "小群", 22);
  students[1] = new Student("怀化学院", "小群", 22);
  System.out.println(students[0].equals(students[1]));


 这两个Student对象的属性相同,但有equals比较会发现不同。如果要对属性比较,自己需要实现equals方法。
 在Student中重写equals方法

 @Override
 public boolean equals(Object otherObject) {
  if (this == otherObject)// 两个对象相同,显然相等
   return true;
  if (otherObject == null)// otherObject为空,返回false
   return false;
  if (getClass() != otherObject.getClass())// 两个类不同,返回false
   return false;
  // 保证otherObject为Student类,接下来判断属性值是否相等
  Student other = (Student) otherObject;
  return this.getAge() == other.getAge()
    && this.getName() == other.getName()
    && this.school == other.school;
 }


 有些人喜欢用(!(otherObject instanceof Student))代替(getClass() != otherObject.getClass())来判断
 otherObject是不是Student类,但这样有一个问题:子类也可以是父类的实例。
 equals应该满足以下5个特性:
 (1)自反性,对任意非空变量x,x.equals(x)必须返回true;
 (2)对称性,x.equals(y)与y.equals(x)返回值应该一样;
 (3)传递性,如果x.equals(y)返回true,y.equals(z)也返回true,则x.equals(z)应该也返回true;
 (4)一致性,如果变量x,y指向的对象没有发生改变,那么重复调用x.equals(y)的返回值应该是一样的;
 (5)对任意的非空变量x, x.equals(null)必须返回false

posted @ 2013-01-06 11:04  CodeMeals  阅读(360)  评论(0编辑  收藏  举报
reliable statistics
Visitors