Java Road to God: Java Interview Preparation (8)

Article Directory

Among the following structures in 4.16 , the highest insertion performance is

4.17 Which of the following structures is most suitable for use as a stack

Insert picture description here

4.18 Among the implementation classes of Map, which ones are ordered and which are disorderly, how to ensure the orderliness of the orderliness, which do you think the orderliness is higher in performance, do you have better or more efficient implementations? the way

  1. The implementation classes of Map are HashMap, LinkedHashMap, TreeMap

  2. HashMap is disordered, LinkedHashMap and TreeMap are both ordered (LinkedHashMap records the order of adding data; TreeMap defaults to natural ascending order)

  3. The underlying storage structure of LinkedHashMap is hash table + linked list, the linked list records the order of adding data

  4. The underlying storage structure of TreeMap is a binary tree, and the in-order traversal of the binary tree ensures the orderliness of the data

  5. LinkedHashMap has higher ordering performance because of the hash table used in the underlying data storage structure

4.19 The code below runs normally most of the time. Under what circumstances will the problem occur? Where is the root cause

import java.util.LinkedList;
public class Stack {
    
    
    LinkedList list = new LinkedList();
    public synchronized void push(Object x) {
    
    
        synchronized (list) {
    
    
            list.addLast(x);
            notify();
        }
    }
    public  synchronized Object pop() throws  Exception{
    
    
        synchronized(list){
    
    
            if(list.size()<=0){
    
    
                wait();
            }
            return list.removeLast( );
        }
    }
}

将if(list.size())改为while(list.size())

4.20 How do TreeMap and TreeSet compare elements when sorting? How the sort() method in the Collections tool class compares elements

TreeSet requires that the class to which the stored object belongs must implement the Comparable interface. This interface provides a compareTo() method for comparing elements. When an element is inserted, this method will be called back to compare the size of the element. TreeMap requires that the keys stored in the key-value pair mapping must implement the Comparable interface to sort the elements according to the key. The sort method of the Collections utility class has two overloaded forms. The first requires the comparison of objects stored in the incoming container to be sorted and implements the Comparable interface to achieve element comparison; the second does not require the elements in the container to be compulsory. It must be comparable, but the second parameter is required to be passed in. The parameter is a subtype of the Comparator interface (the compare method needs to be rewritten to achieve element comparison), which is equivalent to a temporarily defined sorting rule, in fact, the size of the comparison element is injected through the interface The algorithm is also an application of the callback mode.

4.21 How to remove the same objects from the List

public class Test {
    
    
    public static void main(String[] args) {
    
    
        List<String> li1 = new ArrayList<String>();
        li1.add("8");
        li1.add("8");
        li1.add("9");
        li1.add("9");
        li1.add("0");
        System.out.println(li1);
        //方法:将List中数据取出来来存到Set中
        HashSet<String> set = new HashSet<String>();
        for(int i=0;i<li1.size();i++){
    
    
            set.add(li1.get(i));
        }
        System.out.println(set);
    }
   
}

4.22 The implementation classes of Java.util.Map are

1、HashMap

2、Hashtable

3 、 LinkedHashMap

4、TreeMap

4.23 Which of the following statements is correct

4.24 What are the Java containers, and which are synchronous containers? Which are concurrent containers

Synchronized container: refers to thread safety, generally use the synchronized keyword, although the data consistency is guaranteed, but the concurrency is very poor

  • Vactor
  • HashTable
  • Stack
  • Collections.synchronized()

Concurrent container: the efficiency is still high in a multi-threaded environment, reducing the use of locks

  • CopyOnWrieArrayList
  • CopyOnWriteArraySet
  • ConcurrentHashMap
  • ArrayBlockingQueue
  • LinkedBlockingQueue

4.25 Time complexity of inserting and accessing ArrayList and LinkedList

The time complexity of ArrayList lookup is O(1), and the time complexity of insertion is O(n)

The time complexity of LinkedList search is O(n), and the time complexity of insertion is O(1)

4.26 Under what circumstances will HashMap expand? What actions will trigger expansion

HashMap expansion in JDK1.7 needs to meet two conditions

1. When storing a new value, the number of elements in the future is greater than or equal to the threshold

2. When storing new values, there are existing values ​​in the current array

JDK1.8 expansion conditions

After the new value is stored, if the number of elements is greater than the threshold, the capacity will be expanded

What actions will trigger expansion

1、put()

2、merge()

4.27 The execution process of put method in HashMap

The put method of HashMap can be regarded as the core function of HashMap. The data structure of HashMap is an array + linked list. Values ​​are stored in the form of key and value. The values ​​are stored and retrieved by calling the put and get methods.
It maintains an Entry array internally, obtains the hashCode value of the key, shifts it by bitwise AND operation, and then obtains an index value by performing a logical AND operation with the length of the array -1 to determine the position of the data stored in the Entry array. Solve the problem of hash conflicts through linked lists. When a collision occurs, the object will be stored in the next node of the linked list.

4.28 After HashMap detects a hash conflict, will the element be inserted at the end or the beginning of the linked list?

4.29 jdk1.8 uses red-black trees, talk about the characteristics of red-black trees, why do people have to use red-black trees instead of AVL

It is locked in CurrentHashMap. It is actually a read-write lock. If there is a write conflict, it will wait.

If the insertion time is too long, the waiting time will be longer, and the insertion of the red-black tree is faster than the AVL tree!

4.30 What is the difference between the underlying implementation of HashMap and HashTable? HashTble and ConcurrentHashMap

HashTable

  • The bottom-level array + linked list is implemented, neither the key nor the value can be null , thread- safe , the way to achieve thread-safety is to lock the entire HashTable when modifying the data, which is inefficient, and the ConcurrentHashMap is optimized.
  • The initial size is 11 , expansion: newsize = olesize*2+1
  • Method of calculating index: index = (hash & 0x7FFFFFFF)% tab.length

HashMap

  • + Linked list implementation of the underlying array, may be stored null keys and null values , thread unsafe
  • Initial size is 16 , expansion: newsize = oldsize*2, size must be 2 to the power of n
  • Expansion is for the entire Map. Each time the expansion is performed, the elements in the original array are recalculated and re-inserted.
  • After inserting the element, it is judged whether to expand or not, and it may be invalid expansion (if you expand after insertion, if you do not insert it again, invalid expansion will occur)
  • When the total number of elements in the Map exceeds 75% of the Entry array, the expansion operation is triggered. In order to reduce the length of the linked list, the element distribution is more even
  • Calculating index method: index = hash & (tab.length – 1)

ConcurrentHashMap

  • The bottom layer is implemented with a segmented array + linked list, which is thread- safe
  • By dividing the entire Map into N segments, the same thread safety can be provided, but the efficiency is increased by N times, and the default is increased by 16 times. (The read operation is not locked. Since the value variable of HashEntry is volatile, the latest value can also be guaranteed to be read.)
  • Hashtable's synchronized is for the entire Hash table, that is, each time the entire table is locked to allow the thread to monopolize, ConcurrentHashMap allows multiple modification operations to be performed concurrently, and the key lies in the use of lock separation technology
  • Some methods need to span segments, such as size() and containsValue(), they may need to lock the entire table instead of just a segment, which requires all segments to be locked in sequence, and after the operation is completed, all segment locks are released in sequence
  • Expansion: Expansion within the segment (the element in the segment exceeds 75% of the corresponding Entry array length of the segment to trigger expansion, and the entire Map will not be expanded), the detection before insertion does not require expansion, which effectively avoids invalid expansion

4.31 What is the difference between fast failure and safe failure

The safety failure of Iterator is based on copying the underlying collection, therefore, it is not affected by the modification on the source collection.

All collection classes under the java.util package fail fast

All classes under the java.util.concurrent package are safe to fail

The fast fail iterator throws ConcurrentModificationException

Safety failure iterator will never throw such an exception

Guess you like

Origin blog.csdn.net/weixin_54707168/article/details/113975161