黑马程序员技术交流社区

标题: HashSet迭代对象时为什么会拿到哈希值? [打印本页]

作者: 黑马张平    时间: 2012-4-9 21:09
标题: HashSet迭代对象时为什么会拿到哈希值?
import java.util.*;
/*
往HashSet集合中存入自定义对象
姓名和年龄一样视为同一个人。
*/

class  HashSetText
{
        public static void main(String[] args)
        {
                HashSet hs=new HashSet();
                hs.add(new Person("ZhangSan1",21));
                hs.add(new Person("ZhangSan2",22));
                hs.add(new Person("ZhangSan3",23));
                hs.add(new Person("ZhangSan4",24));
                hs.add(new Person("ZhangSan5",25));
                hs.add(new Person("ZhangSan5",25));
                hs.add(new Person("ZhangSan4",23));
                for (Iterator it=hs.iterator();it.hasNext() ; )
                {
                        Object o= it.next();
                        sop(o);
                }
        }
        public static void sop(Object o )
        {System.out.println(o);}
}
class Person
{
        private String name;
        private int age;
        Person(String name, int age)
        {
                this.name=name;
                this.age=age;
        }
        public int hashCode()
        {
//        System.out.println(this.name+"........"+this.age);
        return name.hashCode()+age*5;
        }
        public boolean equals(Object obj)
        {
                if (!(obj instanceof Person))
                {
                        return false;
                }
                Person p=(Person)obj;
//                System.out.println(this.name+"______equals_______"+this.age);
                return this.name.equals(p.name)&&this.age==p.age;
        }
        public String getName()
        {
                return name;
        }
        public int getAge()
        {
                return age;
        }
}


打印结果:
Person@204d72ac
Person@204d72be
Person@204d72a6
Person@204d72b3
Person@204d72b2
还有一个问题,怎么把DOS命令行的内容复制过来?我都 是复制不过来。
作者: 李敏    时间: 2012-4-9 21:24
1. 你用迭代器是,打印的是学生对象。如果学生对象里面没有 重写 toString 方法的话,就会调用父类的toString方法,默认打印的是 类名 @ 十六进制的哈希值。
所以一般在需要输出对象是,就要覆写该方法。
2. 右键----标记------选中需要复制的内容-----回车键------欧了。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2