以下的错误例子,看清了哈希表中的对象只能是同一类型的,否则会抛出classcastexception
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("one");
hs.add(new MyStudent(1,"one"));
hs.add(new MyStudent(1,"one"));
hs.add(new MyStudent(1,"one"));
hs.add(new MyStudent(1,"one"));
Iterator it = hs.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class MyStudent
{
int num;
String name;
MyStudent(int num,String name)
{
this.num = num;
this.name = name;
}
public int hashCode()
{
return num*name.hashCode();
}
public boolean equals(Object o)
{
MyStudent s = (MyStudent)o;
return num == s.num && name.equals(s.name);
}
public String toString()
{
return num+","+name;
}
}