07. Common data structures

Directory Structure

  • 1. What are the commonly used data
  • 2. Description of the data
  • 3. Introduction to the collection data structure
  • 4. Features of collection {List, Set, Map}

1. What are the commonly used data?

  • 1.1 As shown in the figure below: image image

  • 1.2 Common collection data image

2. Description of the data

  • 2.1 Arrays

  • image

    • unordered array
      • Advantages: fast query, if you know the index, you can access it quickly
      • Disadvantages: slow deletion, fixed size
    • sorted array
      • Pros: Faster than unordered array lookup
      • Cons: slow deletes and inserts, fixed size
  • 2.2 Stack

    • Advantages: Provides last-in, first-out access method
    • Disadvantage: accessing other items is slow
    • For example, the management of activity in and out in Android is to use the stack
  • 2.3 Queue

    • Advantages: Provides first-in, first-out access
    • Disadvantage: accessing other items is slow
  • 2.4 Linked list

    • Advantages: fast insertion, fast deletion
    • Disadvantage: slow search (one node check)
  • 2.5 Binary tree

    • Advantages: Fast lookup, insertion, deletion (balanced binary tree)
    • Disadvantage: complex deletion algorithm
  • 2.6 Red-Black Trees

    • Advantages: lookup, insertion, deletion are fast, the tree is always balanced (local adjustment)
    • Disadvantage: complex algorithm
  • 2.7 Hash table

    • Advantages: If the keyword is known, the access speed is extremely fast, and the insertion is fast
    • Disadvantages: slow deletion, slow access if the keyword is not known, insufficient storage space usage
  • 2.8 Heaps

    • Advantages: fast insertion and deletion, fast access to items with the largest data
    • Disadvantage: slow access to other data items
  • 2.9 Figure

    • Pros: Models the real world
    • Disadvantage: Some algorithms are slow and complex

3. Introduction to the collection data structure

  • 3.1 Set collection [Generally used are TreeSet and HashSet]
  • 3.1.1 TreeSet
    • TreeSet is implemented based on a binary tree, that is, TreeMap. The data placed in it cannot be repeated and cannot be null. The compareTo() method can be rewritten to determine the size of the elements, so as to sort in ascending order.
public class DataType {
    public static void main(String[] args){
        Set<Integer> treeSet = new TreeSet<>(new MyComparator());
        treeSet.add(1);
        treeSet.add(3);
        treeSet.add(2);
        for(Integer i : treeSet){
            System.out.println(i);
        }
    }

    static class MyComparator implements Comparator<Integer>{
        @Override
        public int compare(Integer o1, Integer o2) {
            if(o1 < o2 ){
                return -1;
            }
            if(o1 == o2 ){
                return 0;
            }
            if(o1 > o2 ){
                return 1;
            }
            return 0;
        }
    }
}
执行结果:
1
2
3
  • 3.1.2 HashSet
    • HashSet determines the storage location according to hashCode, which is implemented by HashMap, so the object must implement the hashCode() method. The stored data is disordered and cannot be repeated. Null can be stored, but only one can be stored.
public class DataType {
    public static void main(String[] args){
        Set<String> set = new HashSet<>();
        set.add("1");
        set.add("2");
        set.add(null);
        set.add("1");
        for(String s : set){
            System.out.println(s);
        }
    }
}
运行结果
null
1
2
  • 3.2 List collection [List is more commonly used ArrayList and LinkedList, and there is a similar Vector]
  • 3.2.1 ArrayList
    • It is implemented using dynamic arrays, which is more efficient for random get and set of data or insertion or deletion of a small amount of data. ArrayList is thread-unsafe, and is faster without considering thread-safety. ArrayList insert data can be repeated, but also in order, according to the order of insertion.
    • To read data according to the serial number, you only need to directly obtain the data of the corresponding foot table of the array
public class ListTest {
    public static void main(String[] args){
        List<String> arrayList = new ArrayList<>();
        arrayList.add("1");
        arrayList.add("1");
        arrayList.add("2");
        arrayList.remove("1");
        for(String s : arrayList){
            System.out.println(s);
        }
    }
}
内部使用动态数组来实现

/**Shared empty array instance used for empty instances.*/
private static final Object[] EMPTY_ELEMENTDATA = {};
public ArrayList() {
         this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
  • 3.2.2 LinkedList
    • Internally, it is implemented in the form of a linked list, which is faster when inserting a large amount of data.
    • LinkedList obtains data according to the serial number, which is traversed in two parts. If the serial number is less than half of the total length, it traverses from the head of the linked list until the corresponding serial number is found. If the sequence number is greater than half of the total length, traverse forward from the end of the linked list until the corresponding sequence number is found. get data.
    • linked list implementation code
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;

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++;
}

往容器最前面添加元素的代码
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++;
}
根据序号获取数据:
public E get(int index) {
    //判断index序号是否是合法的
    checkElementIndex(index);
    return node(index).item;
}
Node<E> node(int index) {
    // assert isElementIndex(index);
    if (index < (size >> 1)) {//判断序号在总长度一半之前还是之后
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}
  • 3.2.3 Vector
    • The usage and internal implementation of Vector are basically the same as ArrayList, except that it adds synchronization in add(), remove(), get() and other methods. So it is thread safe. But the use efficiency is not as good as ArrayList.

4.Map集合【HashMap,TreeMap,HashTable】

  • 4.1 HashMap
    • HashMap is implemented based on a hash linked list. In simple terms, a hash value is calculated according to the key, and a storage index is determined, but the hash value may conflict and repeat, so if the conflicting hash value needs to be in the form of a linked list in the same An index is stored.
Map<String, String> hashMap = new HashMap<>();
hashMap.put("1", "a");//存储
hashMap.put("2", "b");

hashMap.remove("1");//根据key来删除
hashMap.get("2");//根据key获取

//map的遍历,有很多方法遍历,这里只列举一种。
for(Map.Entry<String, String> entry : hashMap.entrySet()){
    entry.getKey();//获取key
    entry.getValue();//获取value
}
  • 4.2 TreeMap

    • The use of TreeMap is roughly similar to that of HashMap, but the internal implementation is based on the red-black tree. A red-black tree is a balanced and ordered binary tree, and the insertion and deletion queries of TreeMap are carried out according to the rules of the red-black tree.
  • 4.3 HashTable

    • Both HashMap and TreeMap are thread-unsafe, and may cause data errors during multi-threaded operations. Hashtable is thread safe. Other internal implementations are the same as HashMap.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325025791&siteId=291194637
Recommended