容器 第二节 重写equals和hashCode方法
来源:互联网 发布:怎么添加打印机端口 编辑:程序博客网 时间:2024/06/10 06:54
容器类对象在调用remove、contains等方法时需要比较对象是否相等,这会涉及到对象类型的equals方法(主要用)和hashCode方法(当对象用在Map接口里面作为键,即作为字典的索引时才会用hashCode这个方法,因为hashCode这个方法效率会更高);对于自定义的类型(这里自定义了Name这个类),需要重写equals和hashCode方法以实现自定义的对象相等规则。
什么时候才需要重写equals和hashCode方法呢:自定义的类如这里的Name类,得重写equals和Name这两种方法,如果是字符串例如该程序中的“f1”“l1”,她的内部已经自己写了equals和hashCode方法,这里就不用再重写了,new Integer(100)也不用写equals和hashCode方法,因为Integer类中也自己重写了这两种方法
注意:相等的对象应该具有相等的hashCodes,hashCode非常适合做索引
这里在Name类添加的equals和hashCode方法如下:
public boolean equals(Object obj){
if(obj instanceof Name){
Name name =(Name) obj;
return (firstName.equals(name.firstName))&&(lastName.equals(name.lastName));
}
return super.equals(obj);
}
public int hashCode(){
return firstName.hashCode();
完整的程序如下:
输出结果是:
true
[ ]
刚试了一下,如果把重写的equals方法和hashCode方法注掉,输出结果就会是false [f1 l1],所以要想删除new Name("f1","l1")这个对象,必须得重写equals方法和hashCode方法
- 容器 第二节 重写equals和hashCode方法
- 重写hashCode和equals方法
- 重写equals和hashCode方法
- 重写hashCode和equals方法
- 重写hashcode和equals方法
- 重写equals() 和 hashCode()方法
- 重写hashCode()和equals()方法
- 重写equals和hashcode方法
- HashCode和equals方法重写
- 重写equals() 和 hashCode()方法
- 重写hashCode()方法和重写equals()方法
- 重写equals()方法和hashcode()方法
- 重写equals方法和hashcode方法
- HashMap中重写hashCode和equals方法
- java重写equals和hashCode方法
- 为什么要重写hashcode和equals方法
- 重写object中的hashcode和equals方法
- 重写hashCode()和equals()方法的必要
- SharePoint 2013 REST 服务使用简介
- 简单文章发布系统(4)
- Linux命令英文全称
- poj 2243 Knight Moves
- UVA - 10801 Lift Hopping (Dijkstra)
- 容器 第二节 重写equals和hashCode方法
- hibernate之13.hql(二)
- GitHub 优秀的 Android 开源项目
- HDU 5011 Game 【Nim博弈】
- codeforces 476c Dreamoon and Sums
- opengl教程
- CodeForces 486C Palindrome Transformation
- libevent2源码 min_heap
- Uva 644-Immediate Decodability(串)