`
uule
  • 浏览: 6311615 次
  • 性别: Icon_minigender_1
  • 来自: 一片神奇的土地
社区版块
存档分类
最新评论

HashSet

 
阅读更多

 

Set 是不包含重复元素的集合。可以更加正式地表达为,在 set 里面的元素 e1,e2, 不允许 e1.equals(e2), 而且最多有一个 null 元素。

Set 的主要方法如下,可以看出 List 和 Set 在方法上的区别了, List 能够根据类似于 index ,来找到元素的方法,而 set 只管往集合里面放东西,并不管其插入的顺序, List 有比较严格的插入顺序。

 

HashSet 的基本数据结构是 HashMap  HashMap 的基本数据结构是哈希表和链表,在构造函数上可以参见HashMap 的工作原理,和 HashMap 一样,影响性能的因素包括: set 的初始化容量大小,容量因子,和HashCode 的构造.

 

Set不包含重复元素,而HashMap的Key也不可重复,故其可使用HashMap实现。

 

成员变量:

 

    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>();
    }

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * the specified initial capacity and the specified load factor.
     *
     * @param      initialCapacity   the initial capacity of the hash map
     * @param      loadFactor        the load factor of the hash map
     * @throws     IllegalArgumentException if the initial capacity is less
     *             than zero, or if the load factor is nonpositive
     */
    public HashSet(int initialCapacity, float loadFactor) {
	map = new HashMap<E,Object>(initialCapacity, loadFactor);
    }

    public HashSet(int initialCapacity) {
	map = new HashMap<E,Object>(initialCapacity);
    }
 

主要方法:

 

public boolean add(E e) {
	return map.put(e, PRESENT)==null;
    }

public boolean remove(Object o) {
	return map.remove(o)==PRESENT;
    }

public void clear() {
	map.clear();
    }

public boolean contains(Object o) {
	return map.containsKey(o);
    }

/**
     * Returns an iterator over the elements in this set.  The elements
     * are returned in no particular order.
     *
     * @return an Iterator over the elements in this set
     * @see ConcurrentModificationException
     */
    public Iterator<E> iterator() {
	return map.keySet().iterator();
    }

    
 

更详细可参考:http://zhangshixi.iteye.com/blog/673143

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics