为什么在以哈希表为内部存储方式的结构中,重写完hashCode()后,还要重写equals()

//经典例子:为什么在以哈希表为内部存储方式的结构中,重写完hashCode()后,还要重写equals()???

生气生气

import  java.util.*;

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
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只懒得睁眼的猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值