怎样写一个尽可能优雅的equals方法

来源:互联网 发布:广联达软件开发待遇 编辑:程序博客网 时间:2024/04/29 07:55
package com.amber.ivy;
/**
 * 编写一个尽可能通用的equals方法
 * @author ivyamber
 *
 */
public class EqualsDemo {


public static void main(String[] args) {
Object ivy = new Person("ivy", 21);
Object amber = new Person("ivy", 21);
System.out.println(ivy.equals(amber));
}
}
/**
 * 人类
 * @author ivyamber
 *
 */
class Person
{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean equals(Person obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}

}

如果人的名字和年纪一样我们就认为这是一个人(当然,这是不对的)。但是这个例子中,将返回false,因为其实Person类没有覆盖Object类的equals方法,所以ivy,amber是Object对象就会调用Object的equals方法。所以写equals方法第一点,覆盖Object方法,最好加一个@override以免覆盖出错。

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;//同一个引用一定是同一个对象
if (obj == null)//一定要保证obj不是null,否则下面会报错
return false;
if (getClass() != obj.getClass())//有人认为应该使用instanceof,getClass不符合置换规则。我是觉得如果相等的概念每个子类都不一样就用getClass 要是取决于父类就//用instanceof
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

0 0
原创粉丝点击