Java - HashSet

来源:互联网 发布:最优化可行方向 编辑:程序博客网 时间:2024/05/21 14:41

Set 集合用法和 Collection 一致,常用类 : HashSet 和 TreeSet 。
Set 特点: 元素无序(存储和取出顺序不一定一致),元素不重复。
HashSet :底层数据结构是哈希表,按照哈希值存储。

HashSet 如何判断唯一 ?
通过元素的两个方法 HashSet 和equals来完成,先判断HashCode 是否一致,再判断是否是同一对象。而 ArrayList 集合则 只通过 equals 判断。

例子:

import java.util.*;//自定义 Person 对象,通过判断 Person 对象的 姓名 和 年龄 ,不重复的元素 存储到 HashSetclass HashSetDemo{    public static void main(String[] args)    {        HashSet hs = new HashSet();        hs.add(new Person("a1",11));        hs.add(new Person("a1",11));        hs.add(new Person("a2",11));        hs.add(new Person("a3",13));        hs.add(new Person("a3",13));        hs.add(new Person("a4",13));        hs.remove(new Person("a3",13));        Iterator it = hs.iterator();        while(it.hasNext())        {            Person p =(Person)it.next();            sop(p.getName()+","+p.getAge());        }        sop(hs.contains(new Person("a1",11)));    }    public static void sop(Object o)    {        System.out.println(o);    }}class Person{    private String name;    private int age ;    public String getName()    {        return this.name;    }    public int getAge()    {        return this.age;    }    Person(String name,int age)    {        this.name = name;        this.age = age ;    }    public int hashCode()    {        return this.name.hashCode()+this.age*11;    }    public boolean equals(Object o)    {        if(!(o instanceof Person))            return false;        Person p = (Person)o;        return this.name.equals(p.name)&&this.age==p.age;    }}
0 0
原创粉丝点击