Java容器_Set_HashSet源码分析

来源:互联网 发布:淘宝网无法加入购物车 编辑:程序博客网 时间:2024/05/22 11:53
Set接口是上文介绍的容器的第四个接口,也是最后一个接口,也是实现起来最容易的接口。

(1)Set接口是Collection接口的子接口,Set接口没有提供额外的方法;
(2)Set接口的特性是容器类中的元素是没有顺序的,而且不可以重复;
(3)Set容器可以与数学中“集合”的概念相对应;
(4)JDK API中所提供的Set 容器类有HashSet,TreeSet等。

打开Set接口的源码:

public interface Set<E> extends Collection<E> {    int size();
正如上文所说,没有新定义额外的方法。
打开HashSet源码:
public class HashSet<E>    extends AbstractSet<E>    implements Set<E>, Cloneable, java.io.Serializable{    // HashSet是使用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();    /**     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has     * default initial capacity (16) and load factor (0.75).     */    public HashSet() {        map = new HashMap<>();    }   /**     * Adds the specified element to this set if it is not already present.     * More formally, adds the specified element <tt>e</tt> to this set if     * this set contains no element <tt>e2</tt> such that     * <tt>(e==null ? e2==null : e.equals(e2))</tt>.     * If this set already contains the element, the call leaves the set     * unchanged and returns <tt>false</tt>.     *     * @param e element to be added to this set     * @return <tt>true</tt> if this set did not already contain the specified     * element     */    public boolean add(E e) {        return map.put(e, PRESENT)==null;    }

好了,HashSet的实现比较简单,就是HashMap的简单操作,把对象作为Key值赋给Map对象,value使用PRESENT。另外,set没有get方法取值,只能用迭代器遍历查询。

package com.ws.list;import java.util.HashSet;import java.util.Iterator;import java.util.Set;public class testiterator {public static void main(String[] args) {Set set=new HashSet();set.add("aaa");set.add("aab");Iterator iterator=set.iterator();while (iterator.hasNext()){String str = (String) iterator.next();System.out.println(str);}for (Iterator iterator2=set.iterator();iterator2.hasNext();){String str = (String) iterator2.next();System.out.println(str);}}}

0 0
原创粉丝点击