Collection of basic study notes

List interface

The stored objects are in order and repeatable

ArrayList

Store objects like an array, and you need to build a new array every time you add or delete them, which is suitable for multiple queries

The underlying principle

Construction method: construct an empty array, and construct an object array with a default size of 10 after passing in the parameters

add: If it does not exceed the size of the array, add

Over, enter the grow expansion method

    public boolean add(E e) {
    
    
    	//ensureCapacityInternal在新版本不再使用
        ensureCapacityInternal(size + 1); 
        elementData[size++] = e;
        return true;
    }

First compare the incoming size with 1.5 times the original array size (bitwise operation), get the larger value of the two, and
then compare the larger value with the set maximum array length (INTEGER.MAX_VALUE-8).
If it does not exceed, Construct an array with a larger value and copy the original array

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    private void grow(int minCapacity) {
    
    
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

If it exceeds, perform huge capacity processing.
Compare the incoming size with the maximum array length, if it is greater, construct an array of INTEGER.MAX_VALUE length, if it is less, construct an array of maximum array length

    private static int hugeCapacity(int minCapacity) {
    
    
        if (minCapacity < 0) 
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

remove: delete data, move the following number forward

LinkedList

Store objects like a linked list, suitable for multiple additions and deletions

Vector

Ancient implementation class of List, thread safe

Collection collection traversal

1. Use Iterator.
2. Use foreach to traverse the collection. You cannot modify the data. You can only query.
3. Use the forEach method.
Use the forEachRemaining method of the iterator.
Use the forEach method of the collection.
Both have functional interfaces and are used with Lambda expressions.

RandomAccess interface

There are no attributes or methods in the interface, just a logo

If it is connected, it means that this type supports random access and can look up data like an array.
If it is not connected, it means that this type of data does not support random access, and it can only look up data in a linked list.

Set interface

The stored objects are disordered and cannot be repeated

HashSet

Use the hash algorithm for storage. After the address of the input object is calculated, if it is empty, it will be stored directly, and it cannot be stored if it is not empty.

TreeSet

Use red-black trees for storage, so it can be sorted.
Sorting is divided into: natural sorting, custom sorting

Sorting principle

Natural ordering

When constructing the storage object class, implement the Comparable interface, and rewrite the compareTo method, and use the add method in the collection to automatically sort

Select sort

When defining the collection object, pass in the custom comparator Compartor, you need to implement the compare method in the comparator, and use the add method in the collection to automatically sort

Map interface

Store key-value pairs

HashMap

Use the hash algorithm for storage. After the input object calculates the address, if it is empty, it will be stored directly. If it is not empty, it will be regarded as a hash conflict

LinkedHashSet

Use linked list to store data

The underlying principle

Basic attributes

Threshold: 8, the length of the linked list exceeds 8 to expand, if the length of the array is not less than 64, the linked list is converted into a red-black tree.
Maximum capacity: 2 to the 30th power
Fill factor: 0.75, expansion starts when the storage node exceeds the array size multiplied by the fill factor.
Default Size: 16, the size of the array being constructed for the first time

What is stored in the hash table

Store Node nodes, the node implements the Entry interface, so the hash table can return key-value pairs. The
hash table opens up a continuous memory space for storing Node nodes, that is, Node[]
can store Node and TreeNode, linked list and red-black tree

How to resolve hash conflicts

1. Linked list method
2. Development addressing method, linear addressing, secondary addressing
3, re-hashing
4, domain building method

Source code

hash: hashcode and hashcode binary shift right 16 bits

    static final int hash(Object key) {
    
    
      int h;
      return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  }

put: call the putVal method

putVal:
If the size is empty or 0, call the resize method to expand

Call hash to calculate the hash value, insert if the address is empty

Replace if the key value is the same

Search through the linked list or red-black tree, and replace if the key value is the same

Insert to the end, when the length of the linked list is greater than 8, try to convert to a red-black tree

Determine whether you need to resize or expand the capacity by the length of the array and the fill factor

public V put(K key, V value) {
    
    
    return putVal(hash(key), key, value, false, true);
}

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;
        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) 
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) {
    
    
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

resize: expansion mechanism

treeifyBin: Linked list to red-black tree

Red black tree

The red-black tree is a highly balanced binary search tree that satisfies the following properties:

1. The root node and leaf nodes are both black.
2. The child nodes of the red node are all black.
3. The path from each node to the leaf node contains the same number of black nodes.

The red-black tree relies on left-handed, right-handed and discolored to maintain the nature of the red-black tree when adding and deleting

TreeMap

Use red-black trees to store key-value pairs

HashTable

Use the synchronized keyword to ensure thread safety

ConcurrentHashMap

Before: Use segmented lock + synchronized to ensure thread safety
Now: Array + linked list/red-black binary tree, use CAS and synchronized to ensure thread safety

Map collection traversal

1. The forEach method of the collection itself
2. Map has its own method of returning a set collection, which can be traversed by the method of Collection collection traversal
keySet, valueSet, entrySet
3, for loop traversal
4, iterator

Guess you like

Origin blog.csdn.net/sekever/article/details/114705537