且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

java HashSet类实现哈希表

更新时间:2022-08-13 08:14:44

 /*HashSet 类实现哈希表(散列表)
我们应该为插入到 哈希表的各个对象重写 hashCode()和equals() 方法 
String 类重写的   hashCode() 是根据字符串计算的  
Object 类的       hashCode() 是根据内存地址计算散列地址
哈希表只能通过迭代器迭代元素 Iterator
*/
import java.util.*;
class HashTest
{
 public static void main(String []args)
 {
  HashSet hs=new  HashSet() ;  //HashSet 实现了Set接口不能 包含重复值
  hs.add(new Student(1,"li")); 
  hs.add(new Student(2,"wang"));
  hs.add(new Student(1,"wangwu"));
  hs.add(new Student(1,"li"));
  Iterator i=hs.iterator(); //获得哈希表迭代器
  while(i.hasNext())  //通过迭代器输出元素
  {
   System.out.println(i.next());
  }
  
  
  
  
 }
 
 
}
class  Student
{
 int num ;
 String name;
 Student(int num,String name)
 {
  this.num=num;
  this.name=name;
 }
 public String toString ()  //重写toString
 {
  return num+":"+name;
 }
 
 public int hashCode()   //重写 hashCode()  
 {
  return num*name.hashCode();
 }
 public boolean equals(Object o) //重写equals()方法
 {
  Student s=(Student)o;
    return num==s.num && name.equals(s.name);
 }
 
}