当前位置: 代码迷 >> Java相关 >> [求助]HashSet的问题
  详细解决方案

[求助]HashSet的问题

热度:97   发布时间:2007-03-21 16:55:00.0
[求助]HashSet的问题

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;
}
}
其中红色部分不知为什么要这样写,而不是return num=s.name.equals(s.name);
而且上面这段代码也在编译时出现错误.信息如下:


搜索更多相关的解决方案: HashSet  

----------------解决方案--------------------------------------------------------
JDK1.5以后加了泛型 ,你没有加,就会有警告

像你要在里面加入Student,可以这样声明

HashSet<Student> hs=new HashSet<Student>();

这样就只能往里面加Student了,并且你取出来的时候,也不用cast了,直接取就是Student对象
----------------解决方案--------------------------------------------------------
谢谢千里,按你说的,已经解决了
----------------解决方案--------------------------------------------------------
建议楼主练练抓图。。。
----------------解决方案--------------------------------------------------------
建议楼上在技术区少灌点水


----------------解决方案--------------------------------------------------------
  相关解决方案