首页 > 移动平台 > 详细

android开发重写equals方法和hashCode方法的通用写法记录

时间:2019-12-09 11:19:39      阅读:114      评论:0      收藏:0      [点我收藏+]
实际开发我们有时需要判断比较两个对象是否相同,通常做法是重写对象的equals方法。
但重写equals方法时,一般我们也会重写hashCode方法。其实如果该对象不会当作Map里的key,不重写hashCode方法也是没啥影响的。
想重写hashCode方法不知道该怎么写?下面是重写equals方法时,也重写hashCode方法的通用写法:

final
class ResourceCacheKey implements Key { private final Key sourceKey; private final Key signature; private final int width; private final int height;private final Options options; @Override public boolean equals(Object o) { if (o instanceof ResourceCacheKey) { ResourceCacheKey other = (ResourceCacheKey) o; return height == other.height && width == other.width&& sourceKey.equals(other.sourceKey) && signature.equals(other.signature) && options.equals(other.options); } return false; } @Override public int hashCode() { int result = sourceKey.hashCode(); result = 31 * result + signature.hashCode(); result = 31 * result + width; result = 31 * result + height; result = 31 * result + options.hashCode(); return result; } }

 

android开发重写equals方法和hashCode方法的通用写法记录

原文:https://www.cnblogs.com/yongfengnice/p/12009547.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!