如有同名且年龄相同的视作是同一个人,搞了好久没找到错误。。。
代码如下:
- 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;
- }
- }
复制代码
|
|