Java集合JDK8

Java集合可以分为Collection和Map两种体系;

Collection接口:单列集合,存储一个个的对象

Collection接口下有两个子接口:List接口Set接口
List:存储有序、可重复的对象
Set:存储无序、不可重复的对象

List接口的实现类:ArrayList、LinkedList、Vector

ArrayList:作为List的主要实现类,线程不安全,效率高;底层使用数组transient Object[] elementData;来存储数据。

/**
 *当你调用无参构造器时,会为你自动创建一个容量为10的list
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//当你调用有参构造器时,则会为你创建一个长度为参数值的list
/**
 * Constructs an empty list with the specified initial capacity.
 *
 * @param  initialCapacity  the initial capacity of the list
 * @throws IllegalArgumentException if the specified initial capacity
 *         is negative
 */
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);
    }
}

LinkedList底层使用双向链表存储数据,对于频繁的增删效率比ArrayList快,线程不安全。

private static class Node<E> {
    E item;
    Node<E> next;
    Node<E> prev;

    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}
/**
 * Pointer to first node.
 * Invariant: (first == null && last == null) ||
 *            (first.prev == null && first.item != null)
 */
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;
}
/**
 * Links e as last element.
 */
void linkLast(E e) {
    final Node<E> l = last;//将链表中最后的对象last赋给l
    final Node<E> newNode = new Node<>(l, e, null);//将传入的数据创建一个新的对象,并将l作为新对象的前一个,新对象的后一个置为空
    last = newNode;//然后将新建的对象赋给链表中的末尾指针
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}

Vector作为古老实现类,线程安全,但是效率低下,底层跟ArrayList使用数组transient Object[] elementData;来存储数据。

Set接口的实现类:HashSet、LinkedHashSet、TreeSet

Set的无序性:不等于随机性,存储数据在底层数组中并不是按照数组索引顺序添加,而是根据哈希值确定数据的存放位置;
Set的不可重复性:添加元素按照equals()方法进行判断,不同元素返回true;相同元素只能添加一个
HashSet作为Set接口的主要实现类,线程不安全,可以存储null值

//HashSet底层是HashMap
public HashSet() {
    map = new HashMap<>();
}
//HashSet里数据的存储结构
	final int hash;//记录哈希值
	final K key;     //记录存放内容
	V value;	// Dummy value to associate with an Object in the backing Map
			//虚拟值,来与后台传入的key相关联
	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 boolean add(E e) {
    return map.put(e, PRESENT)==null;
}
//进入put方法
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
//计算哈希值
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//进入putVal方法
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)//根据数组长度和哈希值相与得到存放位置,若为空直接存放
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;//看看P是不是我们要存储的值
        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 {//遍历链表,若最后一个的next为空,则直接挂上添加即可
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    //若链表上的数量大于8个,则将链表转换为红黑树
                    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;
}

LinkedHashSet作为HashSet的子类,在添加数据的同时,每个数据维护了两个引用,分别记录此数据的前一个数据和后一个数据,遍历时可以按照添加时的时候遍历

//LinkedHashSet的数据存储结构,比HashSet多了两个属性,分别用来记录前一个和个后一个数据
static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    Entry(int hash, K key, V value, Node<K,V> next) {
        super(hash, key, value, next);
    }
}
//添加过程跟HashSet类似,只是多了两个指针指向前后两个值

注:向Set中添加的数据,所在的类一定要重写hashCode()和equals()方法,才能体现出Set的无序性和不可重复性。

Map接口:双列集合,存储一对对具有映射关系的键值对

Map接口的实现类有HashMap,LinkedHashMap ,TreeMap,Hashtable,Properties

HashMap 作为主要实现类,线程不安全,效率高,可以存储null的key和value;由于HashSet和HashMap的底层原理一样,所以HashMap的添加过程跟HashSet一样,只是要value值实例化了。

LinkedHashMap 跟LinkedHashSet过程差不多。

猜你喜欢

转载自blog.csdn.net/fighting32/article/details/107035418