java 的Object的equals方法
2013-07-18 15:05
471 查看
Java Object equals方法
/** *
*/
package freewill.objectequals;
/**
* @author freewill
* @see Core Java page161
* @desc getClass实现方式,另有instance of实现方式,根据不同场景使用。
*/
public class Employee {
private String name;
private int salary;
private String hireDay;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getHireDay() {
return hireDay;
}
public void setHireDay(String hireDay) {
this.hireDay = hireDay;
}
@Override
public boolean equals(Object obj) {
// a quick test to see if the objects are identical
if (this == obj)
return true;
// must return false if the explicit parameter is null
if (obj == null)
return false;
// if the class don't match,they can't be equal
if (getClass() != obj.getClass())
return false;
// now we know obj is non-null Employee
Employee other = (Employee) obj;
// test whether the fileds have identical values
return name.equals(other.name) && salary == other.salary
&& hireDay.equals(other.salary);
}
}
Java语言规范要求equals方法具有下面的特性:
1.自反性:对于任何非空引用x,x.equals(x)应该返回true。
2.对称性:对于任何引用x和y,当且仅当y.equals(x)返回true,x.equals(y)也应该返回true。
3.传递性:对于任何引用x、y和z,如果x.equals(y)返回true,y.equals(z)返回true,x.equals(z)也应该返回true。
4.一致性:如果x和y引用的对象没有发生变化,反复调用x.equals(y)应该返回同样的结果。
5.对于任意非空引用x,x.equals(null)应该返回false。
相关文章推荐
- java基础:Object的equals方法
- (二十五)Java工具类EqualsBuilder协助Object.equals(object)方法详解
- (二十五)Java工具类EqualsBuilder协助Object.equals(object)方法详解
- Java中的hashCode()方法与equals(Object)方法
- (二十五)Java工具类EqualsBuilder协助Object.equals(object)方法详解
- 【Java基础之Object类(一)】Java中Object类中的所有方法(toString、equals、hashCode、clone、finalize、wait和notify等)详解(转载)
- java Object对象中hashCode和equals方法学习
- JAVA源码分析之---Object类(二)---hashCode,equals,clone方法的使用
- Java Object类(equals方法)
- (二十五)Java工具类EqualsBuilder协助Object.equals(object)方法详解
- Java 基础一些代码练习笔记(object-equals 方法)
- (二十五)Java工具类EqualsBuilder协助Object.equals(object)方法详解
- Java中的Object-equals()方法
- (二十五)Java工具类EqualsBuilder协助Object.equals(object)方法详解
- JAVA Object对象(toString、equals、hashCode方法)、String类、StringBuffer、StringBuider、System、Runtime、Date、Mat
- java Object 的equals方法的复写
- 重写Java Object对象的hashCode和equals方法实现集合元素按内容判重
- (二十五)Java工具类EqualsBuilder协助Object.equals(object)方法详解
- JAVA基础知识回顾(基本数据类型,switch参数,equals与==的区别,Object有哪些公用方法)-1
- 重写Java Object对象的hashCode和equals方法实现集合元素按内容判重