HashSet底层原理

HashSet底层完全就是在HashMap基础上包装了一层,只不过存储的时候value是存储的一个Object静态常量,取的时候只返回key

因为底层是hashmap,存储的又是key,所以没有get()方法,只能通过遍历获取

 

源码解读

    private transient HashMap map;

    
    public HashSet() {
        map = new HashMap<>();
    }

    public HashSet(Collection c) {
        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
    }

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

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

    
    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

   
    public Iterator iterator() {
        return map.keySet().iterator();
    }

    
    public int size() {
        return map.size();
    }

    
    public boolean isEmpty() {
        return map.isEmpty();
    }

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

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

    

 

你可能感兴趣的:(java)