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

来源:互联网 发布:新注册域名 访问 编辑:程序博客网 时间:2024/04/29 16:35

//经典例子:为什么在以哈希表为内部存储方式的结构中,重写完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