一个重写equals()和hashCode()方法的例子
来源:互联网 发布:网络歌手排行榜2008 编辑:程序博客网 时间:2024/05/21 23:33
下面是一个根据业务键实现equals()与hashCode()的例子。实际中需要根据实际的需求,决定如何利用相关的业务键来组合以重写这两个方法。
- public class Cat
- {
- private String name;
- private String birthday;
- public Cat()
- {
- }
- public void setName(String name)
- {
- this.name = name;
- }
- public String getName()
- {
- return name;
- }
- public void setBirthday(String birthday)
- {
- this.birthday = birthday;
- }
- public String getBirthday()
- {
- return birthday;
- }
- //重写equals方法
- public boolean equals(Object other)
- {
- if(this == other)
- {
- //如果引用地址相同,即引用的是同一个对象,就返回true
- return true;
- }
- //如果other不是Cat类的实例,返回false
- if(!(other instanceOf Cat))
- {
- return false;
- }
- final Cat cat = (Cat)other;
- //name值不同,返回false
- if(!getName().equals(cat.getName())
- return false;
- //birthday值不同,返回false
- if(!getBirthday().equals(cat.getBirthday()))
- return false;
- return true;
- }
- //重写hashCode()方法
- public int hashCode()
- {
- int result = getName().hashCode();
- result = 29 * result + getBirthday().hashCode();
- return result;
- }
- }
重写父类方法的原则:可以重写方法的实现内容,成员的存取权限(只能扩大,不能缩小),或是成员的返回值类型(但此时子类的返回值类型必须是父类返回值类型的子类型)。
- 一个重写equals()和hashCode()方法的例子
- 重写hashCode()和equals()方法的必要
- equals 和 hashCode 的重写方法
- equals和hashCode的重写方法
- 重写hashCode和equals方法
- 重写equals和hashCode方法
- 重写hashCode和equals方法
- 重写hashcode和equals方法
- 重写equals() 和 hashCode()方法
- 重写hashCode()和equals()方法
- 重写equals和hashcode方法
- HashCode和equals方法重写
- 重写equals() 和 hashCode()方法
- 重写hashCode()方法和重写equals()方法
- Hashcode和equals的重写
- equals和hashcode的重写
- java 重写类的equals方法和hashcode方法
- 重写equals方法和hashcode方法的作用
- javascript call()和apply()
- Linux基本操作 8----- 文件的排序+分割+合并+归档等
- AC自动机——1 Trie树(字典树)介绍
- VIJOS 1532 区间
- hibernate中关联关系的小结
- 一个重写equals()和hashCode()方法的例子
- 做工行支付怎样获取工行返回数据,及取货地址跳转
- Java工作流引擎:jBPM、Activiti以及SWF
- OCP-1Z0-053-V12.02-162题
- cookies 与session的区别和详解
- Hibernate的其他几种检索方式:
- OCP-1Z0-052-V8.02-55题
- VS2010编译工具默认路径问题
- getClass的反射机制getSimpleName