Chinaunix首页 | 论坛 | 博客
  • 博客访问: 96294
  • 博文数量: 54
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 510
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-30 00:36
文章分类

全部博文(54)

文章存档

2010年(1)

2009年(52)

2008年(1)

我的朋友

分类: Java

2009-10-07 18:35:56

实现Set接口的hash table(哈希表),依靠HashMap来实现的。
我们应该为要存放到散列表的各个对象定义hashCode()和equals()。
import java.util.*;
class HashSetTest
{
 public static void main(String[] args)
 {
  HashSet hs=new HashSet();
  /*hs.add("one");
  hs.add("two");
  hs.add("three");
  hs.add("one");*/
  hs.add(new Student(1,"zhangsan"));
  hs.add(new Student(2,"lisi"));
  hs.add(new Student(3,"wangwu"));
  hs.add(new Student(1,"zhangsan"));
  
  Iterator it=hs.iterator();
  while(it.hasNext())
  {
   System.out.println(it.next());
  }
 }
}
class Student
{
 int num;
 String name;
 Student(int num,String name)
 {
  this.num=num;
  this.name=name;
 }
 public int hashCode()
 {
  return num*name.hashCode();
 }
 public boolean equals(Object o)
 {
  Student s=(Student)o;
  return num==s.num && name.equals(s.name);
 }
 public String toString()
 {
  return num+":"+name;
 }
}
阅读(446) | 评论(0) | 转发(0) |
0

上一篇:ArrayList和LinkedList的比较

下一篇:散列表

给主人留下些什么吧!~~