为什么在以哈希表为内部存储方式的结构中,重写完hashCode()后,还要重写equals()
来源:互联网 发布:新注册域名 访问 编辑:程序博客网 时间:2024/04/29 16:35
//经典例子:为什么在以哈希表为内部存储方式的结构中,重写完hashCode()后,还要重写equals()???
class Student
{
public int id;
public String name;
public int age;
public Student(int id,String name,int age)
{
this.id = id;
this.name = name;
this.age = age;
}
public String toString()
{
return id + name + age;
}
public int hashCode() //通过哈希码值找到存放的地址只是第一步
{
return id * age;
}
public boolean equals(Object obj)
{
Student ss = (Student)obj;
//return (this.id == ss.id ) && (this.name == ss.name) && (this.age==ss.age);
return this.name == ss.name; //如果是这样的话,new Student(2,"张明阳",24)与new Student(48,"张明阳",1)两个对象只能有一个存放在容器里面
}
}
public class zhang5
{
public static void main(String[] args)
{
HashSet LL = new HashSet();
LL.add(new Student(48,"张明阳",1)); //这个例子也证明了同一块哈希码地址处存放的并不只是一个元素
LL.add(new Student(2,"张明阳",24)); //48 == 48
LL.add(new Student(2,"张明阳",24));//一旦发现内容相同,后面的对象就不存放了
LL.add(new Student(2011480147,"小红",28));
System.out.println(new Student(2011480169,"张明阳",24).hashCode());
System.out.println(new Student(2011480169,"张明阳",24).hashCode());
System.out.println(LL);
}
}
/*
程序最后输出的结果是:
1030883800
1030883800
[48张明阳1, 2011480147小红28]
*/
0 0
- 为什么在以哈希表为内部存储方式的结构中,重写完hashCode()后,还要重写equals()
- 为什么重写了equals方法后,还要重写hashcode方法
- 为什么重写了equals(),还要重写hashCode()?
- 为什么要在重写了equals方法时还要重写hashcode方法
- 新建的类对象,在重写equals方法后为什么要重写hashcode方法?
- 为什么重写了equals()之后还要重写hashCode()
- list\set等容器(集合)那里重写equals为什么还要重写hashCode方法
- HashMap与HashCode()、equals()的关系---在HashMap中实现以对象为键(key)
- HashMap与HashCode()、equals()的关系---在HashMap中实现以对象为键(key)
- 为什么在重写equals方法时都要重写hashCode
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- iOS开发——图片选取
- 简单逆向分析使用案例(4)--CrackMe_03.exe 修改bug
- Android学习笔记——持久化技术
- 动态代理
- 初识Jenkins
- 为什么在以哈希表为内部存储方式的结构中,重写完hashCode()后,还要重写equals()
- gcc/g++搜索路径
- iOS -- 查看系统版本(objective-c)
- 10012---JavaScript--保留关键字
- 接下来要研究的几个点
- GIT快速入门
- 分位数回归的r语言代码
- Android开发中退出程序几种方法
- 密码学之密匙交换