黑马程序员技术交流社区
标题:
谁帮我看一下,HashSet存储自定义元素出错了
[打印本页]
作者:
zgjswp
时间:
2015-3-18 23:33
标题:
谁帮我看一下,HashSet存储自定义元素出错了
如有同名且年龄相同的视作是同一个人,搞了好久没找到错误。。。
代码如下:
public class HashSetTest {
public static void main(String[] args) {
HashSet hs = new HashSet();
hs.add(new Student("lisi", 11));
hs.add(new Student("zhangsan", 12));
hs.add(new Student("qiansan", 16));
hs.add(new Student("zhaoliu", 13));
hs.add(new Student("zhaoliu", 13));
hs.add(new Student("qiansan", 16));
Iterator it = hs.iterator();
while (it.hasNext()) {
Student stu = (Student) it.next();
sop(stu.getName() + "..." + stu.getAge());
}
}
public static void sop(Object obj) {
System.out.println(obj);
}
}
class Student {
private String name;
private int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
public int hasCode() {
return name.hashCode() + age * 20;
}
public boolean equals(Object obj) {
if (!(obj instanceof Student))
return false;
Student stu = (Student)obj;
return this.name.equals(stu.name) && this.age == stu.age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2