关于SET的小问题
import java.util.*;
class TextSet
{
public static void main(String [] args)
{
HashSet <Student> h=new HashSet <Student> ();
h.add(new Student(2, "aaa "));
h.add(new Student(2, "aaa "));
h.add(new Student(1, "LHX "));
Iterator i=h.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()
{
return num+ ": "+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 int hashCode() {
return num * (name.hashCode());
}
hashCode,大小写错了!
------解决方案--------------------又是一个大小写的问题:
public int hashCode() //在你的程序里hsahCode是小写,就这个原因,以后细心点就行了!
{
return num*(name.hashCode());
}