hashset

来源:互联网 发布:淘宝店下架的宝贝在哪里 编辑:程序博客网 时间:2024/06/05 20:55

hashset

import java.util.HashSet;import java.util.Set;public class hashset_test {public static void main(String[] args) {Set s1=new HashSet<>();s1.add("aaa");s1.add("aaa");s1.add("bbb");System.out.println(s1.size());}}
输出结果为2


HashSet是实现Set接口的一个类,具有以下的特点:不能保证元素的排列顺序,顺序有可能发生变化,元素不允许重复
HashSet 是哈希表实现的,HashSet中的数据是无序的,可以放入null,但只能放入一个null,两者中的值都不能重复,就如数据库中唯一约束 
HashSet要求放入的对象必须实现HashCode()方法,放入的对象,是以hashcode码作为标识的,而具有相同内容的String对象,hashcode是一样,所以放入的内容不能重复。但是同一个类的对象可以放入不同的实例
HashSet不能添加重复的元素,当调用add(Object)方法时候,首先会调用Object的hashCode方法判hashCode是否已经存在,如不存在则直接插入元素;如果已存在则调用Object对象的equals方法判断是否返回true,如果为true则说明元素已经存在,如为false则插入元素。

以下转载自:http://www.hijava.org/2010/02/how-to-judge-object-repeated-for-hashset/

查看了JDK源码,发现HashSet竟然是借助HashMap来实现的,利用HashMap中Key的唯一性,来保证HashSet中不出现重复值。具体参见代码:

public class HashSet<E>    extends AbstractSet<E>    implements Set<E>, Cloneable, java.io.Serializable{    private transient HashMap<E,Object> map;    // Dummy value to associate with an Object in the backing Map    private static final Object PRESENT = new Object();    public HashSet() {    map = new HashMap<E,Object>();    }    public boolean contains(Object o) {    return map.containsKey(o);    }    public boolean add(E e) {    return map.put(e, PRESENT)==null;    }

由此可见,HashSet中的元素实际上是作为HashMap中的Key存放在HashMap中的。下面是HashMap类中的put方法:
public V put(K key, V value) {    if (key == null)        return putForNullKey(value);    int hash = hash(key.hashCode());    int i = indexFor(hash, table.length);    for (Entry<K,V> e = table[i]; e != null; e = e.next) {        Object k;        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {        V oldValue = e.value;        e.value = value;        e.recordAccess(this);        return oldValue;        }    }}

从这段代码中可以看出,HashMap中的Key是根据对象的hashCode() 和 euqals()来判断是否唯一的。

结论:为了保证HashSet中的对象不会出现重复值,在被存放元素的类中必须要重写hashCode()和equals()这两个方法。