day14-13-集合框架(HashSet存储自定义对象)

2020-06-22  本文已影响0人  姗婷

往hashSet集合中存入自定义对象,同姓名同年龄,视为同一个人。为重复元素。

HashSet是如何保证元素唯一性的呢?
如果元素的HashCode值相同,才会判断equals是否为true。
如果元素的hashCode值不同,才会调用equals方法。

注意:对于判断元素是否存在、添加、删除元素等操作,依赖的方法是元素的hashcode和equals方法
Arryalist依赖于equals方法判断。


import java.util.*;



class Person
{
    private String name;
    private int age;
    Person(String name,int age)
    {   
        this.name = name;
        this.age = age;
    }
    //hashCode()
    public int hashCode()
    {
        //System.out.println(this.name+"hashCode");
        return name.hashCode()+age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    
    //复写Object的equals,Object中的equals是判断地址值是否相同。
    public boolean equals(Object obj)
    {
        //System.out.println(this.name+"....."+this.name);
        //instanceof 运算符只能用作对象的判断。
        if(!(obj instanceof Person))
        {
            return false;
        }
        Person p = (Person)obj;
        //System.out.println(this.name+"....."+this.name);

        return this.name.equals(p.name)&& this.age ==p.age;
    }
}
class HashsetTest
{
    public static void main(String[] args) 
    {
            HashSet hs = new HashSet();

            hs.add(newPerson("a1",11));
            hs.add(newPerson("a2",12));
            hs.add(newPerson("a3",13));
            hs.add(newPerson("a2",12));
            sop("a1:"+hs.contains(new Person("a2",12)));
            hs.remove(new Person("a3",13));


            Iterator it  =hs.iterator();
            while (it.hasNext())
            {
                Person p = (Person)it.next();
                sop(p.getName()+"::" && p.getAge);
            }
    }

    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读