10 minutes to see the basics of Java: perhaps you also know such a collection

Reference blog link 1

Reference blog link 2

1. Basic knowledge

1. Collection framework interface

Insert picture description here
The basic interface of the collection: Collection and Map

2. Comparison of collections and arrays

  1. Features of the array

    1. The array is essentially a continuous memory space, used to record multiple data of the same type;
    2. Once the array is declared, the memory space is fixed;
    3. Insert and delete operations are inconvenient, and may move a large number of elements resulting in too low efficiency;
    4. Support subscript access, random access can be achieved;
    5. The elements in the array can be basic data types or reference data types;
  2. Features of the collection

    1. The memory space can be discontinuous and the data types can be different;
    2. The memory space of the collection can be adjusted dynamically;
    3. The insertion and deletion of the collection can not move a large number of elements;
    4. Partially supports subscript access, and some does not;
    5. The elements in the collection must be reference data types

3. Collection common methods

  1. Common example methods
//  添加
boolean add(e);
 
//  用于将参数指定集合中的所有元素放入当前集合中。
boolean addAll(Collection<? extends E> c);

// 用于从当前集合中删除参数指定的元素。
boolean remove(Object o);

// 用于从当前集合中删除参数指定集合中的所有元素。
boolean removeAll(Collection<?> c);

// 用于将当前集合中的所有元素移除。
void clear()

// 用于判断当前集合中是否包含参数指定的单个元素。(o==null ? e==null : o.equals(e))
boolean contains(Object o); 

// 用于判断当前集合中是否包含参数指定集合中的所有元素。
boolean containsAll(Collection<?> c);

// 用于判断当前集合是否为空。
boolean isEmpty();

// 用于返回当前集合中元素的个数。
int size()

// 用于获取当前集合和参数集合的交集并保留到当前集合中。若当前集合中的内容发生了更改则返回true,否则返回false。
boolean retainAll(Collection<?> c);
  1. Common class methods
// 将所有指定的元素添加到指定的集合。
static boolean addAll(Collection<? super T> c, T... elements);

// 将所有元素从一个列表复制到另一个列表中。
static void copy(List<? super T> dest, List<? extends T> src);

// 交换指定列表中指定位置的元素。 
static void swap(List<?> list, int i, int j);

// 反转指定列表中元素的顺序。 
static void reverse(List<?> list);

List collection (emphasis)

  1. basic concept

    The java.util.List interface is a sub-interface of the Collection interface. Elements are placed in order, and repeats are allowed. The main implementation classes of this interface are: ArrayList class, LinkedList class, Stack class and Vector class.

    • The bottom layer of the ArrayList class is implemented using dynamic arrays, so it is not convenient to add or delete, and it is convenient to access the elements;
    • The bottom layer of the LinkedList class is implemented using a linked list, so it is easy to add and delete, and it is inconvenient to access elements;
    • Among them, the bottom layer of the Stack (stack) class is implemented using a dynamic array, used to describe a data structure with last in first out characteristics, referred to as LIFO (last in first out).
    • The bottom of the Vector class is implemented using dynamic arrays. Compared with the ArrayList class, it is an early class and belongs to the thread-safe class. Therefore, the efficiency is relatively low. It is recommended to use the ArrayList class instead.
  2. Common methods

void add(int index, E element) 
        - 用于将元素element插入到当前集合中index指向的位置。
boolean addAll(int index, Collection<? extends E> c) 
        - 用于将集合c中所有元素插入到当前集合中index指向的位置。
E remove(int index) 
        - 用于将index位置的元素从当前集合移除。
        - 返回被删除的元素值,下标不合理时会产生下标越界异常。
E set(int index, E element) 
        - 使用element元素替换当前集合中index位置的元素,返回被替换的元素。
E get(int index) 
        - 用于返回当前集合中下标为index位置的元素。
List<E> subList(int fromIndex, int toIndex) 
        - 用于返回当前集合中从fromIndex(包含)toIndex(不包含)之间的部分视图。
        - 返回的集合和当前集合共用同一块内存区域。

Queue common methods

   boolean offer(E e) - 将参数指定的元素e插入到当前队列的末尾。
       - 若插入成功则返回true,否则返回false。
   E poll() - 用于从当前队列的队首移除一个元素并返回。
       - 若当前队列为空,则返回null。
   E peek() - 用于获取当前队列的队首元素并返回。
       - 若当前队列为空,则返回null。

Second, common problems

1. What is the difference between Array and ArrayList? When should I use Array instead of ArrayList?

1. Differences :

  • Array can contain basic data types and object types, ArrayList can only contain object types.
  • The size of Array is fixed, and the size of ArrayList changes dynamically.
  • ArrayList provides more methods and features, such as: addAll (), removeAll (), iterator () and so on.

2.
For basic types of data, the collection uses automatic boxing to reduce the coding workload. However, this approach is relatively slow when dealing with basic data types of fixed size.

2. What is hash?

  • Hash, generally translated as hash, hash, or transliteration as hash, is to convert any length of input through a hash algorithm into a fixed-length output, the output is the hash value.
  • Common hash algorithms:
  • MD4, MD5, md5 are more complex than MD4, slower, but safer, and perform better in anti-analysis and anti-differential
  • Commonly used construction methods of hash table:
  • Direct addressing method: take the keyword or a linear function of the keyword as the hash address.
  • Square method: take the middle of the square of the key as the hash address.
  • Random number method: Choose a random function and take the random function of the key as its hash address.
  • Divided remainder method: The remainder after the key is divided by a number p not greater than the length m of the hash table is the hash address.

3. The underlying principles of HashMap and ConcurrentHashMap

  • HashMap is based on the principle of hashing. We store and retrieve objects through put () and get () methods. When we pass the key-value pair to the put () method,
    it calls the hashCode () method of the key object to calculate the hashcode, and then finds the bucket location to store the value object.
    When obtaining an object, find the correct key-value pair through the key object's equals () method, and then return the value object.
    HashMap uses a linked list to solve the collision problem. When a collision occurs, the object will be stored in the next node of the linked list.
    HashMap stores key-value pair objects in each linked list node.
  • HashMap can be synchronized by the following statement:
    • Map m = Collections.synchronizeMap(hashMap);
  • Conclusion
    Hashtable and HashMap have several major differences: thread safety and speed. Use Hashtable only when you need complete thread safety, and if you use Java 5 or above, use ConcurrentHashMap.

JDK 7

  1. Hashmap-> Array + linked list
  • key-> key.hashcode ()% array size-> get the array subscript, when the obtained array of subscripts has a value, a one-way linked list is introduced. Insert into the head quickly.
  • The reference to Entry is stored in the array, Entry is the entity of KV, Entry array
  • Thread unsafe
  • Added synchronized in hashtable and lock
  1. ConcurrentHashmap array + linked list
  • The segment lock segment is stored in the array. The
    segment stores the hashentry (same as entry) array. Each segment inherits the reentrant lock ReentrantLock, which can also control the lock. Several elements can share a lock.
    Insert picture description here

JDK 8

  1. HashMap-> array + linked list + red black tree

  2. concurrentHashmap

    • ConcurrentHashMap in JDK8 refers to the implementation of JDK8 HashMap, which uses the array + linked list + red-black tree implementation to design, a large number of internal CAS operations.
    • JDK8 completely abandoned the Segment and adopted Node, and its design idea is no longer the segmented lock idea in JDK1.7.
    • Node: The data structure that holds the key, value and key hash value. Both value and next are modified with volatile to ensure concurrent visibility.
    • ConcurrentHashMap in JDK8 will convert the linked list into a red-black tree when the length of the linked list is greater than a certain threshold to further improve its search performance.
    • Summary: The implementation in JDK8 is also the idea of ​​lock separation. It divides the lock more finely than the segment (JDK1.5). As long as the hash does not conflict, there will be no concurrent lock acquisition.
      It first uses the lock-free operation CAS to insert the head node. If the insertion fails, it indicates that another thread has been inserted into the head node, and the operation is repeated in a loop. If the head node already exists,
      the head node lock is acquired through synchronized, and subsequent operations are performed. Performance is improved again than segment segment lock.

4. Talk about the classification and common situation of map

  • Java defines an interface java.util.Map for the mapping in the data structure; it has four implementation classes, namely HashMap , Hashtable , LinkedHashMap and TreeMap .
  • Map is mainly used to store health value pairs, get the value according to the key, so the key is not allowed to repeat (overlap is repeated), but the value is allowed to repeat.
  1. Hashmap is one of the most commonly used Maps. It stores data according to the key's HashCode value, and can directly obtain its value according to the key. It has a fast access speed. When traversing, the order of obtaining data is completely random. HashMap only allows the key of one record to be Null; the value of multiple records is Null; HashMap does not support synchronization of threads, that is, multiple threads can write HashMap at the same time at any time; it may cause data inconsistency. If you need synchronization, you can use the SynchronizedMap method of Collections to make HashMap have the ability to synchronize, or use ConcurrentHashMap.
  2. Hashtable is similar to HashMap, it inherits from the Dictionary class, the difference is: it does not allow the record key or value is empty; it supports thread synchronization, that is,
    only one thread can write Hashtable at any time , so it also causes Hashtable to write Entering time will be slow.
  3. LinkedHashMap is a subclass of HashMap, which saves the insertion order of records. When using Iterator to traverse LinkedHashMap, the first obtained record must be
    inserted first . You can also use parameters with construction to sort by the number of applications. When traversing, it will be slower than HashMap, but there is one exception. When the capacity of HashMap is large and the
    actual data is small, the traversal may be slower than LinkedHashMap, because the traversal speed of LinkedHashMap is only related to the actual data, and has nothing to do with the capacity.
    The traversal speed of HashMap is related to his capacity.
  4. TreeMap implements the SortMap interface, which can sort the records it saves by key. The default is to sort the key values ​​in ascending order. You can also specify a sorting comparator. When iterator is used to
    traverse the TreeMap, the records obtained are sorted.
  • Common situation In
    general, we use HashMap the most, inserting, deleting and locating elements in the Map, HashMap is the best choice. But if you want to traverse the keys in natural order or custom order, then TreeMap will be better. If you need to output the same order as the input, then LinkedHashMap can be used, it can also be arranged in the order of reading.
    • HashMap is one of the most commonly used Maps. It stores data according to the hashCode value of the key, and can directly obtain its value according to the key, with fast access speed. HashMap only allows the key of one record to be NULL at most, and allows the value of multiple records to be NULL. HashMap does not support thread synchronization, that is, there can be multiple threads writing HashMap at the same time, which may cause data inconsistency. If you need to synchronize, you can use the SynchronizedMap method of Collections to make HashMap have the ability to synchronize.
    • Hashtable is similar to HashMap , except that it does not allow recorded keys or values ​​to be empty; it supports synchronization of threads, that is, only one thread can write to Hashtable at any one time, which also causes Hashtable to be slower when writing.
    • LinkedHashMap saves the insertion order of the records. When iterating through LinkedHashMap with Iterator, the records obtained first must be inserted first.
    • When traversing, it will be slower than HashMap. TreeMap can sort the records it saves according to the key. The default is to sort in ascending order. You can also specify a sorting comparator. When using Iterator to traverse the TreeMap, the resulting records are sorted.

5. Way to traverse the map

  1. Most common
for (Map.Entry<Object, Object> entry : map.entrySet()) {
	
	System.out.println("key=" + entry.getKey() + ",value=" + entry.getValue());
	
}
  1. If only key or value is needed
// 遍历key 使用 keySet()
for (String key : map.keySet()) {
	
	System.out.println("key=" + key);
	
}

// 遍历value 使用 values()
for (Object value : map.values()) {
	
	System.out.println("value=" + value);
	
}
  1. Use Iterator to traverse the Map

Tip : During the remove operation during the traversal, only the iterator traversal method can be used. Other traversals will throw exceptions (by the way, list can be traversed to complete the remove operation through the Iterator method, and calling the remove method of the list will throw an exception)

Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();

while (entries.hasNext()) {
	
	Entry<String, Object> entry = entries.next();

	System.out.println("key=" + entry.getKey() + ",value=" + entry.getValue());
	
}
  1. Traversing through the key to find the value, shortcomings, low efficiency, the value itself from the key is a time-consuming operation.
for (String key : map.keySet()) {

	Object value = map.get(key);

	System.out.println("key=" + key + ",value=" + value);

}

Write at the end

If you think this article is helpful to you, you can give me a compliment. Your attention and support are my biggest encouragement.

If you have any suggestions and comments on the article, please leave a message to tell me, and look forward to your feedback.

Published 14 original articles · Like 16 · Visits 682

Guess you like

Origin blog.csdn.net/coding_sleep/article/details/105564703