import java.util.*; public class HashSetTest { public static void main(String[] args) { HashSet hss
我是想看看hashset,因为用String两个相同的String只会存贮一个,但是自己声明的student,虽然得到的hashcode相同,而且eqaul返回的也是tr...
我是想看看hashset,因为用String两个相同的String只会存贮一个,但是自己声明的student,虽然得到的hashcode相同,而且eqaul返回的也是true,但是还是会将两个student放入到hashcode中,实在不知道为什么,求高人指教
import java.util.*;
public class HashSetTest {
public static void main(String[] args)
{
HashSet hss = new HashSet();
hss.add("one");
hss.add("one");
System.out.println(hss.size());
HashSet hs = new HashSet();
hs.add(new Student(1,"one"));
hs.add(new Student(1,"one"));
hs.add(new Student(3,"one"));
hs.add(new Student(4,"four"));
System.out.println(new Student(1,"one").HashCode());
System.out.println(new Student(1,"one").HashCode());
Iterator it = hs.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
System.out.println(hs.size());
}
}
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 o1 = (Student) o;
return num == o1.num && name == o1.name;
}
public String toString()
{
return "name:=" + name;
}
} 展开
import java.util.*;
public class HashSetTest {
public static void main(String[] args)
{
HashSet hss = new HashSet();
hss.add("one");
hss.add("one");
System.out.println(hss.size());
HashSet hs = new HashSet();
hs.add(new Student(1,"one"));
hs.add(new Student(1,"one"));
hs.add(new Student(3,"one"));
hs.add(new Student(4,"four"));
System.out.println(new Student(1,"one").HashCode());
System.out.println(new Student(1,"one").HashCode());
Iterator it = hs.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
System.out.println(hs.size());
}
}
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 o1 = (Student) o;
return num == o1.num && name == o1.name;
}
public String toString()
{
return "name:=" + name;
}
} 展开
3个回答
展开全部
你的方法名为HashCode()方法,不是重写父类的hashCode()方法该为下面的就可以了
//要重写父类的 hashCode()方法
public int hashCode() {
return num* name.hashCode() ;
}
//要重写父类的 hashCode()方法
public int hashCode() {
return num* name.hashCode() ;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
new过后他们的内存地址不一样,hashcode是根据内存地址返回哈希吗的
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询