黑马程序员技术交流社区

标题: HashSet小程序 [打印本页]

作者: 熊忠元    时间: 2015-7-14 21:05
标题: HashSet小程序
/*
需求:往HashSet集合中存入自定义对象
姓名年龄相同的为同一个人,为重复元素
*/

import java.util.*;
class HashSetDemo
{
        public static void sop(Object obj)
        {
                System.out.println(obj);
        }
        public static void main(String[] args)
        {
                HashSet hs = new HashSet();
                hs.add(new Person("lisi01",23));
                hs.add(new Person("lisi02",21));
                hs.add(new Person("lisi03",22));
                hs.add(new Person("lisi03",22));
                //sop(hs);
                sop(hs.contains(new Person("lisi01",23)));
                Iterator it = hs.iterator();
                while (it.hasNext())
                {
                        Object obj = it.next();
                        Person p = (Person)obj;
                        sop(p.getName()+"::"+p.getAge());
                }
        }
}
class Person
{
        private String name;
        private int age;
        Person(String name,int age)
        {
                this.name = name;
                this.age = age;
        }
        public String getName()
        {
                return name;
        }
        public int  getAge()
        {
                return age;
        }
        public int hashCode()
        {
                System.out.println(this.name+"---hashCode---");
                return this.name.hashCode()+this.age;
        }
       
        public boolean equals(Object obj)
        {
                //if(! (obj intanceof        Person ))
                        //return false;
                Person p = (Person)obj;
                System.out.println(this.name+"----compareto----"+p.name);
                return (this.name.equals(p.name))&&(this.age==p.age);
        }
}





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