ArrayList源码解析和HashMap源码解析

ArrayList 初始化长度,以及长度变化

初始化长度为0

  public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
这是默认静态常量为空所有,所以默认构造ArrayList长度为0

add增加原理,永远不会增加失败

   public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
   private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

 private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

remove删除原理:通过System.arraycopy克隆数组,返回删除元素

    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index); //1.记录下标对应的对象

        int numMoved = size - index - 1; //2.从哪里开始克隆
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved); //从index下一个元素开始克隆到最后一个元素
        elementData[--size] = null; // clear to let GC do its work  删除最后一个位置,GC回收

        return oldValue;
    }

hasNext和next原理:hasNext判断是否当前下标等于容器的大小,next指针移动

   int cursor;       // index of next element to return 当前下标
   int lastRet = -1; // index of last element returned; -1 if no such
   int expectedModCount = modCount;

     Itr() {}

     public boolean hasNext() {
         return cursor != size; //判断是否当前下标等于容器的大小
     }

     @SuppressWarnings("unchecked")
     public E next() {
         checkForComodification();
         int i = cursor;
         if (i >= size) //不能越界
             throw new NoSuchElementException();
         Object[] elementData = ArrayList.this.elementData;
         if (i >= elementData.length)//不能越界
             throw new ConcurrentModificationException();
         cursor = i + 1; //下标+1
         return (E) elementData[lastRet = i];
     }

Map集合实现类对比

在这里插入图片描述
在这里插入图片描述

哈希表

在这里插入图片描述

put方法增加原理图解

在这里插入图片描述

 /**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length; //1、resize默认长度为16,散列因子0.75f
        if ((p = tab[i = (n - 1) & hash]) == null) //2、(n - 1) & hash取模运算
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            //如果哈希值相等,就覆盖
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // 如果表中已经存在该key,就覆盖掉
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

猜你喜欢

转载自blog.csdn.net/qq_43206800/article/details/108301720
今日推荐