当前位置: 代码迷 >> Java相关 >> [求助]HashSet为什么存上相同的内容了??
  详细解决方案

[求助]HashSet为什么存上相同的内容了??

热度:143   发布时间:2007-03-07 19:40:15.0
[求助]HashSet为什么存上相同的内容了??



文件:HashSetTest.java


import java.util.*;

public class HashSetTest
{
public static void main(String[] args)
{
HashSet<Student> hs = new HashSet<Student>();
hs.add(new Student("Dreamm",20)); //重复的
hs.add(new Student("张三",20));
hs.add(new Student("Dreamm",20)); //重复的
hs.add(new Student("Dreamming",20));
hs.add(new Student("MY.L",20));

for(Student s : hs)
{
System.out.println("name: " + s.getName());
System.out.println("age: " + s.getAge());
}

System.out.println("长度是:" + hs.size()); //这里为什么会打印5啊?hs中有一对重复的呀,不是应该4吗?
}
}

class Student
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

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

----------------解决方案--------------------------------------------------------
回复:(limaoyuan)[求助]HashSet为什么存上相同的内...
因为你的 Student 类 没有提供 equest 和 hashcode方法.
你的hashset类把你输入的所有东西全认为不等
----------------解决方案--------------------------------------------------------
楼上讲的没错。
JAVA中原来的“相等”未必就与你理解的“相等”是一回事.你必须通过覆写equals方法来表示你的“相等”
----------------解决方案--------------------------------------------------------

噢耶!明白了,谢二位~


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