美文网首页
java集合数据结构汇总

java集合数据结构汇总

作者: hdychi | 来源:发表于2018-07-20 11:45 被阅读0次

    一、Set

    HashSet其实是用了HashMap的数据结构。HashMap的数据结构是一个数组+链表的形式。

    关于HashMap数据结构的具体实现、以及扩容,参考博客:https://www.jianshu.com/p/8b372f3a195d/

    TreeSet用了TreeMap的数据结构,TreeMap的本质是一个红黑树,TreeMap类里存着根节点:

    private transient Entry<K,V> root;
    

    二、List

    ArrayList内部是数组:

    transient Object[] elementData;
    public boolean add(E e) {
            ensureCapacityInternal(size + 1);  // Increments modCount!!
            elementData[size++] = e;
            return true;
     }
    

    LinkedList内部是链表:

     transient Node<E> first;
    
        /**
         * Pointer to last node.
         * Invariant: (first == null && last == null) ||
         *            (last.next == null && last.item != null)
         */
    transient Node<E> last;
    public boolean add(E e) {
            linkLast(e);
            return true;
    }
     void linkLast(E e) {
            final Node<E> l = last;
            final Node<E> newNode = new Node<>(l, e, null);
            last = newNode;
            if (l == null)
                first = newNode;
            else
                l.next = newNode;
            size++;
            modCount++;
    }
    

    linkLast在链表结尾处添加节点,改变尾节点的next指针指向新节点。

    三、Map

    HashMap的数据结构是一个数组+链表的形式。

    TreeMap的本质是一个红黑树。

    LinkedHashMap的数据结构是HashMap+链表,既用HashMap的数据结构存储,又给每个节点加上before和after维护插入顺序。

    相关文章

      网友评论

          本文标题:java集合数据结构汇总

          本文链接:https://www.haomeiwen.com/subject/yvvfmftx.html