Java集合

概述

集合是存放对象的容器,存放的都是对象的引用,而非对象本身。常见的集合主要有三种——Set(集)、List(列表)和Map(映射)。其中,List和Set实现了 Collection 接口,并且List和Set也是接口,而Map 为独立接口。

一些常用的比较重要的集合实现类:

  • List 的实现类有:ArrayList、Vector、LinkedList
  • Set 的实现类有:HashSet、LinkedHashSet、TreeSet
  • Map 的实现类有:HashMap、Hashtable、Treemap

集合与数组的区别:

  • 数组的长度不可变,集合长度不固定
  • 数组可以存放基本类型和引用类型,集合只能存储引用类型

Map

存放entry键值对,键唯一,一个键对应一个值。键值都可以存放null值。

HashMap

继承AbstractMap,实现了Map。内部数据结构为数组和链表,jdk1.8之后为了提升查询速度加入了红黑树。

重要属性

    
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;	// 默认初始容量大小,一定是2的幂

    static final int MAXIMUM_CAPACITY = 1 << 30;		// 数组最大容量,必须是2的幂&小于等于1 << 30

    static final float DEFAULT_LOAD_FACTOR = 0.75f;		// 默认加载因子

    static final int TREEIFY_THRESHOLD = 8;				// jdk1.8之后,当链表长度大于8时,调整成红黑树

    static final int UNTREEIFY_THRESHOLD = 6;			// jdk1.8之后,当链表长度小于6时,调整成链表

    static final int MIN_TREEIFY_CAPACITY = 64;			// jdk1.8之后,当链表长度大于8时且数组元素个数大于等于64时,调整成红黑树
    
    transient Node<K,V>[] table;			// 存储Node的数组
     
    transient Set<Map.Entry<K,V>> entrySet;	// 存放map里所有的entry,用来进行遍历等操作
    
    transient int size;						// map中元素的数量
    
    transient int modCount;					// 计数器,记录map发生变化的次数
    
    int threshold;							// 触发扩容机制的临界值 = capacity * loadFactor
    
    final float loadFactor;					// 负载因子

什么是Node?

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

通过源码可以看到Node实现Map.Entry,并且重写了Object的toString、hasCode和equals方法,next可以让Node拓展成一个链表

构造方法

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; 
    }
    
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }
    
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

可以看到,HashMap的默认初始容量大小为16,负载因子默认是0.75,但HashMap提供了构造方法可以控制负载因子和初始容量的大小

操作元素,以put为例

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    
    //获取key的hash值,将这个值右移16位在与旧值进行抑或操作  为了减少碰撞
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    
    
    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;
        if ((p = tab[i = (n - 1) & hash]) == null)			//指定位置里没有Node
            tab[i] = newNode(hash, key, value, null);		//往tab里放Node
        else {												//如果指定位置有Node
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))		//判断Node的key是否存在
                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) { // existing mapping for 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;
    }

可以看到Node的hash值是通过key的hash值右移16位在与旧值进行抑或操作得到。

添加元素的时候通过Node的hash值计算出要挂载的位置,如果该位置为空,则会挂载到该位置。如果该位置有元素,则会判断key,key相同则会更新value。如果key不同,则会判断该元素是否为treeNode,是的话就直接挂载。不是的话就会开始遍历链表,判断链表的长度是否大于8,大于会转换成红黑树再挂载元素,否则直接挂载。

当数组table为空或者length为0时,就会触发HashMap的扩容机制。当元素的个数达到threshold时也会触发扩容机制。

为什么Node的hash值是(h = key.hashCode()) ^ (h >>> 16)?

为了保留高位和地位的信息,保留目标值的特征,减少碰撞

扩容机制

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;		//这里
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

可以看到,数组扩容每次都是2倍。为了在取模的时候做优化,判断元素去哪一个位置的时候需要对key进行取模操作,但取模是一个比较耗费性能的操作。当数组的长度总是2的幂的时候,hash % 数组的length == hash & (数组的length - 1),因为 & 是位运算,直接对二进制数据进行计算,性能更高。

HashTable

继承了Dictionary,实现了Map。HashTable是线程安全的。

    public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }

HashTable的方法大多数都添加了synchronized关键字,来实现线程安全。

TreeMap

继承了AbstractMap,实现了Map。

Connection

存放一组对象的,每一个对象都是他的子元素,根据不同的实现有不同的特点。

Iterator:对Collection进行迭代的迭代器,提供了一些迭代操作的方法

  • hasNext:如果仍有元素可以迭代,则返回true
  • next:返回迭代的下一个元素
  • remove:从迭代器指向的Collection中移除迭代器返回的最后一个元素

迭代器使用过程中不可以使用集合的方法改变集合的元素

List

继承了Collection,插入的元素按照插入的顺序排列,可以包含重复的元素。提供了更加强大的迭代器listIterator

ArrayList

继承了AbstractList,实现了List。底层数据结构是数组,所以查询快,增删慢。

重要属性

    private static final int DEFAULT_CAPACITY = 10;		// 默认数组初始长度
    
    private static final Object[] EMPTY_ELEMENTDATA = {};	// 用于空实例的共享空数组实例
    
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};	// 用于默认大小的空实例的共享空数组实例。我们将其与EMPTY_ELEMENTDATA区分开来,以便知道添加第一个元素时需要膨胀多少
    
    transient Object[] elementData;		// 存储ArrayList元素的数组缓冲区.
    
    private int size;					// ArrayList的大小(数组中实际元素个数)

构造方法

    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    
    //指定初始容量
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
    
    //集合参数
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

可以看到,在使用无参构造方法创建时,ArrayList的默认初始容量是10。同样的ArrayList提供了指定初始容量的构造方法和集合作为参数的构造方法。

操作元素,以add方法为例

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {	
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);	// 默认长度10 
        }

        ensureExplicitCapacity(minCapacity);
    }
    
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);						//触发扩容机制
    }

当添加元素时,集合原有元素个数 + 1大于数组长度时,会触发扩容机制。

扩容机制

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);		//新容量为原来的1.5倍
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);	//创建一个长度为newCapacity的新数组
    }

数组的特点就是一旦初始化,长度就是不可改变的。所以ArrayList用Arrays的copyOf方法创建了一个新的数组。

Vector

继承了AbstractList,实现了List。底层数据结构是数组,所以查询快,增删慢。是线程安全的。

重要属性

    protected Object[] elementData;
    
    protected int elementCount;
    
    protected int capacityIncrement;

构造方法

    public Vector() {
        this(10);
    }
    
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }
    
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

Vector的默认初始容量为10,同样提供了指定初始容量的构造方法

    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }
    
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

扩容机制的触发条件和ArrayList的一样

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

同样用了copyOf创建一个新的数组。扩容时为原来容量的2倍。

可以看到,Vector里操作元素的方法都加了synchronized关键字来保证线程安全。

LinkedList

继承了AbstractSequentialList,实现了List。底层数据结构是链表,增删快,查询慢。

    transient int size = 0;
    
    transient Node<E> first;	//指向第一个节点的指针
    
    transient Node<E> last;		//指向最后一个节点的指针
    
    //头插实现
    private void linkFirst(E e) {
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }
    
    //尾插实现
    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++;
    }
    
    //中插实现
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

Set

继承了Collection,元素不可重复且无序。

如何实现元素不重复:依靠hashcode()和equals()方法。先判断hashcode是否相等,相等则通过equals比较

HashSet

继承了AbstractSet,实现了Set。内部数据结构为数组和链表,jdk1.8之后为了提升查询速度加入了红黑树。

    private transient HashMap<E,Object> map;

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

可以看到,HashSet创建了一个HashMap。

LinkedHashSet

继承了HashSet,实现了Set。底层数据结构是双向链表和哈希表,通过链表来保证元素有序。

TreeSet

继承了AbstractSet,实现了NavigableSet{实现了SortedSet[实现了set]}。底层数据结构是红黑树,内部实现对元素自动排序(实现了SortedSet接口),也可以自定义排序规则(元素的对象类型需要实现Comparable接口或者在创建TreeSet时实现Comparator接口)。基于排序实现元素不重复。根据比较的返回值(CompareTo)是否为0来保证元素的唯一性。

posted @ 2020-11-02 21:00  李嘉图_ricardo  阅读(99)  评论(0)    收藏  举报