Item 8 覆盖equals时请遵守通用约定
在覆盖equals方法的时候,你必须要遵守它的通用约定,不遵守,写出来的方法,会出现逻辑错误。下面是约定的内容:
- 自反性。对于任何非null的引用值,x.equals(x)必须返回true。
- 对称性。对于任何非null的引用值x和y,当且仅当y.equals(x)返回true时,x.equals(y)必须返回true。
- 传递性。对于任何非null的引用值x,y和z,如果x.equals(y)返回true,并且y.equals(z)也返回true,那么x.equals(z)也必须返回true。
- 一致性。对于任何非null的引用值x和y,只要equals的比较操作在对象中所用的信息没有被修改,多次调用x.equals(y)就会一致地返回true,或者一致地返回false。
- 对于任何非null的引用值x,x.equals(null)必须返回false。
对称性
public final class CaseInsensitiveString {
private final String s ;
public CaseInsensitiveString(String s) {
if (s == null)
throw new NullPointerException();
this. s = s;
}
// Broken - violates symmetry!
@Override
public boolean equals(Object o) {
if (o instanceof CaseInsensitiveString)
return s.equalsIgnoreCase(((CaseInsensitiveString) o). s);
if (o instanceof String) // One-way interoperability!
return s.equalsIgnoreCase((String) o);
return false;
}
// This version is correct.
// @Override public boolean equals(Object o) {
// return o instanceof CaseInsensitiveString &&
// ((CaseInsensitiveString) o).s.equalsIgnoreCase(s);
// }
public static void main(String[] args) {
CaseInsensitiveString cis = new CaseInsensitiveString("Polish" );
String s = "polish";
System.out.println(cis.equals(s) + " " + s.equals(cis));
}
}
public class ColorPoint extends Point {
private final Color color ;
public ColorPoint( int x, int y, Color color) {
super(x, y);
this.color = color;
}
// Broken - violates symmetry!
@Override
public boolean equals(Object o) {
if (!(o instanceof ColorPoint))
return false ;
return super .equals(o) && ((ColorPoint) o).color == color;
}
// Broken - violates transitivity!
// @Override public boolean equals(Object o) {
// if (!(o instanceof Point))
// return false;
//
// // If o is a normal Point, do a color-blind comparison
// if (!(o instanceof ColorPoint))
// return o.equals(this);
//
// // o is a ColorPoint; do a full comparison
// return super.equals(o) && ((ColorPoint)o).color == color;
// }
public static void main(String[] args) {
// First equals function violates symmetry
Point p = new Point(1, 2);
ColorPoint cp = new ColorPoint(1, 2, Color.RED);
System. out.println(p.equals(cp) + " " + cp.equals(p));
// Second equals function violates transitivity
ColorPoint p1 = new ColorPoint(1, 2, Color.RED);
Point p2 = new Point(1, 2);
ColorPoint p3 = new ColorPoint(1, 2, Color.BLUE);
System. out.printf("%s %s %s%n" , p1.equals(p2), p2.equals(p3),
p1.equals(p3));
}
}
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Point))
return false ;
Point p = (Point) o;
return p.x == x && p.y == y;
}
// See Item 9
@Override
public int hashCode() {
return 31 * x + y ;
}
}
public enum Color {
RED, ORANGE , YELLOW, GREEN, BLUE, INDIGO , VIOLET
}
public class ColorPoint {
private final Point point ;
private final Color color ;
public ColorPoint(int x, int y, Color color) {
if (color == null)
throw new NullPointerException();
point = new Point(x, y);
this.color = color ;
}
/**
* Returns the point -view of this color point.
*/
public Point asPoint() {
return point ;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ColorPoint))
return false ;
ColorPoint cp = (ColorPoint) o;
return cp.point .equals(point ) && cp.color.equals( color);
}
@Override
public int hashCode() {
return point .hashCode() * 33 + color.hashCode();
}
}
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof InetAddress)) {
- return false;
- }
- return Arrays.equals(this.ipaddress, ((InetAddress) obj).ipaddress);
- }
*
@Override
* public boolean equals(Object obj) {
* if (!(obj instanceof InetAddress)) {
* return false;
* }
* return Arrays.equals(this.ipaddress, ((InetAddress) obj).ipaddress);
* }
Item 8 覆盖equals时请遵守通用约定的更多相关文章
- 第8条:覆盖equals时请遵守通用约定
第8条:覆盖equals时请遵守通用约定 引言:尽管Object是一个具体类,但是设计它主要是为了拓展.它所有的非final方法(equals.hashCode.toString.clone和fina ...
- 第八条:覆盖equals时请遵守通用约定
==是物理相等 equals是逻辑相等 因为每个类的实例对象本质上都是唯一的 ,利用物理相等(==)是指一个实例只能相等于它自己. 利用逻辑相等是(equals)指 一个实例是否和另一个实例的某些关键 ...
- 覆盖equals时请遵守通用约定
Object类中非final修饰的方法有equals().hashCode().toString().finalize().clone()1.equals()方法不需要被覆盖的情况:1)实例化的对象只 ...
- 【Effective Java】4、覆盖equals时请遵守通用约定
package cn.xf.cp.ch02.item8.transitivity; public class Point { private final int x; private final in ...
- 第10项:重写equals时请遵守通用约定
重写equals方法看起来似乎很简单,但是有许多重写方式会导致错误,而且后果非常严重.最容易避免这类问题的办法就是不覆盖equals方法,在这种情况下,类的每个实例都只能与它自身相等.如果满足了以 ...
- 覆盖equals方法时请遵守通用约定
覆盖equals方法时请遵守通用约定 覆盖equals方法看起来很简单,但是有许多覆盖方式会导致错误,并且后果很严重.最容易避免这种类问题的方法就是不覆盖equals方法,在这种情况下,类的每个实 ...
- EffectiveJava(8)覆盖equals是要遵守的约定
覆盖equals是要遵守的约定 1.覆盖种类: -类的每个1实例本质上都是唯一的 -不关心类是否提供了"逻辑相等"的测试功能(Random测试是否能随机相同数字) -超类已经覆盖了 ...
- Item 9 覆盖equals时总要覆盖hashCode
为什么覆盖equals时,总要覆盖hashCode? 原因是,根据Object规范: 如果两个对象根据equals(Object)方法比较是相等的,那么调用这两个对象中任意一个对象的hashCod ...
- 重写equals时,遵守的规定
0 正确的equals方法 public class MyClass { // 主要属性1 private int primaryAttr1; // 主要属性2 private int prima ...
随机推荐
- Alpha项目冲刺_博客链接合集
组员 学号 林泽宇(队长) 211606317 李涵 211606365 尹海川 211606388 郏敏杰 211606307 何永康 211606362 陈炳旭 211606353 苏宇翔 211 ...
- 如果jsp表单元素的值为空,如何避免null出现在页面上?
可以写一个简单的函数对空值进行处理,判断值是否为空,如果是空就返回空字符串.实例代码如下: <%! String blanknull(String s) { return (s == null) ...
- hexo设置permalink-避免url中出现中文
hexo博客初始化的url是年月日+题目:year/:month/:day/:title/,这样的url不便与分享,中文会乱吗,而且一旦修改了题目(我相信大部分人的题目都是中文)就会导致之前分享的ur ...
- lintcode-6-合并排序数组
合并排序数组 合并两个排序的整数数组A和B变成一个新的数组. 样例 给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6] 挑战 你能否优化你的算法,如果其中一个 ...
- iOS-UISearchController用法
import "ViewController.h" @interface ViewController ()<UITableViewDelegate,UITableViewD ...
- 统一日志系统 Log4Net/ExceptionLess
一. 写在前面 本文Log4Net介绍了基础的方式,大数据量生产环境不能使用,中等日志量请日志单库. 希望爱技术的你不要错过exceptionless和ELK 第四节开始简单配置大牛们推荐的了Ex ...
- java直接访问JNDI工具代码
import java.sql.*; import java.util.*; import javax.naming.*; import javax.sql.DataSource; public cl ...
- python函数调用关系图(python call graph)
由于要重构项目的部分代码,要整理好主要的函数调用关系,不想自己看代码慢慢画出结构,想找出一种通用的,节省人力的方法得出函数间的调用关系图,于是发现以下几个工具.(内网没装好graphviz,还没真正用 ...
- [LouguT30212]玩游戏
题面在这里 description 对于\(k=1,2,...,t\),求\[\frac{1}{nm}\sum_{i=1}^{n}\sum_{j=1}^{m}(a_i+b_j)^k\] 对\(9982 ...
- BZOJ4557:[JLOI2016/SHOI2016]侦察守卫——题解
https://www.lydsy.com/JudgeOnline/problem.php?id=4557 小R和B神正在玩一款游戏.这款游戏的地图由N个点和N-1条无向边组成,每条无向边连接两个点, ...