关于Object类的equals方法
2013-01-06 11:04
531 查看
equals方法只通过判断两个变量是否指向同一块内存区域来判断相等,
这两个Student对象的属性相同,但有equals比较会发现不同。如果要对属性比较,自己需要实现equals方法。
在Student中重写equals方法
有些人喜欢用(!(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
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
相关文章推荐
- 关于Object类的equals方法和hashCode方法
- 关于Object类中equals方法的重写
- 关于Object类的equals方法和hashCode方法
- 关于Object中的equals方法重写需要注意什么
- 关于“==” 和equals()方法以及String类的一写总结
- Object对象之equals方法
- Java Object类(equals方法)
- 重写Object中的equals方法
- 关于Object中几个方法的override整理
- 关于== 、equals和instanceof方法你想知道的一切——Java
- C#中关于String.Equals(object,object)和(object==object )的比较
- (二十五)Java工具类EqualsBuilder协助Object.equals(object)方法详解
- (二十五)Java工具类EqualsBuilder协助Object.equals(object)方法详解
- 一个关于equals()方法
- 【源码之路】java中关于equals方法和compareTo方法
- 关于HashCode和equals方法在HashSet中的使用
- 关于equals方法的多态题
- 【转】第7篇:Xilium CefGlue 关于 CLR Object 与 JS 交互类库封装报告:全自动注册与反射方法分析
- 关于json解析时异常org.json.JSONException: A JSONObject text must begin with '{' at character 1 of {的解决方法
- 使用Set存储Object对象,重写equals和hashCode方法