Java rookie supply station-common interview short answer questions (2)

table of Contents

1. The characteristics of the three subcategories of List 3

2. The difference between List, Map and Set

3. What is the difference between HashMap and HashTable?

4. The difference between array and linked list

5. Linked list and array usage scenarios

6. What is the difference between ArrayList and Linkedlist in Java?

7. What are the design patterns you know

8. What is the difference between heap and stack

9. Since there is a GC mechanism, why is there still a memory leak 

10 Why is there a GC mechanism in Java? 

11What memory needs to be recycled for Java GC

12. When does Java GC collect garbage?

13. Talk about the native jdbc operation database process?

14. What should I use PreparedStatement? 

15.What is the mechanism of connection pool in relational database?

16. Can the key and value in the map be null?

17. What are the reference types in Java? (Important)


1. The characteristics of the three subcategories of List 3

  • The underlying structure of ArrayList is an array, the underlying query is fast, and the addition and deletion is slow.
  • The underlying structure of LinkedList is a linked list, with fast additions and deletions, and slow queries.
  • The underlying structure of voctor is array thread-safe, and slow additions, deletions, and queries.

2. The difference between List, Map and Set


2.1 Structural features

  • List and Set are collections that store single-column data, and Map is a collection of double-column data such as keys and values;
  • The data stored in the List is in order and repetition is allowed; the data stored in the Map is in no order, its key cannot be repeated, and its value can be repeated.
  • The data stored in the Set is unordered and no repetition is allowed, but the position of the element in the set is determined by the hashcode of the element, and the position is fixed (the Set collection stores data according to the hashcode, so the position is fixed, But the position is not controllable by the user, so the elements in the set are still out of order for the user);

2.2 Implementation class

  • The List interface has three implementation classes (LinkedList: Based on the linked list implementation, the linked list memory is scattered, each element stores its own memory address, but also stores the address of the next element. The linked list is added and deleted quickly, and the search is slow; ArrayList: Based on an array implementation, non- Thread-safe, high efficiency, easy to index, but not easy to insert and delete; Vector: based on array implementation, thread-safe, low efficiency).
  • There are three implementation classes for the Map interface (HashMap: implementation of the Map interface based on a hash table, non-thread-safe, efficient, and supports null values ​​and null keys; HashTable: thread-safe, inefficient, does not support null values ​​and null keys; LinkedHashMap: is a HashMap A subclass of, saves the insertion order of the records; SortMap interface: TreeMap, can sort the records it saves according to the key, the default is the ascending order of the key value).
  • The Set interface has two implementation classes (HashSet: the bottom layer is implemented by HashMap, and no duplicate values ​​in the set are allowed. When using this method, you need to rewrite equals() and hashCode(methods; LinkedHashSet: inherit from HashSet, and also based on LinkedHashMap For implementation, the bottom layer uses LinkedHashMp).

2.3 Difference

  • The objects in the List collection are sorted according to the index position, and there can be duplicate objects. It is allowed to retrieve the objects according to the index position of the object in the collection, for example, through the list.get() method to get the elements in the collection;
  • Each element in the Map contains a key and a value, which appear in pairs, the key object cannot be repeated, and the value object can be repeated;
  • The objects in the Set collection are not sorted in a specific way, and there are no duplicate objects, but its implementation class can sort the objects in the collection in a specific way. For example, the TreeSet class can follow the default order or implement Java.util. The .Comparator<Type> interface customizes the sorting method.


3. What is the difference between HashMap and HashTable?

  • HashMap is thread-unsafe. HashMap is an interface and a sub-interface of Map. It maps keys to worthy objects. It does not allow key values ​​to be repeated. Empty keys and empty values ​​are allowed: due to non-thread safety, HashMap is more efficient HashTable is more efficient
  • HashTable is a thread-safe collection and does not allow null values ​​to be used as a key value or Value value; HashTable is sychronize, and it is not necessary to synchronize its methods when accessed by multiple threads, while HashMap is accessed by multiple threads. You need to synchronize its methods yourself;
     

4. The difference between array and linked list

 

  • The array stores the elements continuously in the memory; its advantages: because the data is stored continuously and the memory addresses are continuous, it is more efficient when looking for data; its disadvantages: before storing, we need to apply-block continuous The memory space, and the size of its space must be determined when compiling. When running, the size of the space cannot be changed as you need to increase or decrease. When the data is relatively large, it may be out of bounds. When the data is relatively small, it may be wasted. Memory space. When changing the number of data, the efficiency of adding, inserting, and deleting data is relatively low
  • The linked list dynamically applies for memory space. It is not necessary to apply for the size of the memory in advance like an array. You only need to apply for the linked list when you use it. Dynamically apply or delete memory space as needed. It is more flexible than arrays for data addition, deletion and insertion. . There is also that the data in the linked list can be at any location in the memory, and the data can be associated through the application (that is, the pointer of the existing element is connected)


5. Linked list and array usage scenarios

 

  • Array application scenarios: data is relatively small; the operation that is often done is to access data elements by sequence number; arrays are easier to implement and are supported by any high-level language; the constructed linear table is more stable.
  • Linked list application scenarios: it is difficult to estimate the length or scale of the linear list; frequently insert and delete operations; construct a dynamic linear list.
     

6. What is the difference between ArrayList and Linkedlist in Java?

  • ArrayList and Vector use the implementation of arrays. It can be considered that ArrayList or Vector encapsulates operations on internal arrays, such as adding, deleting, inserting new elements or data expansion and redirection to the array.
  • LinkedList uses a circular doubly linked list data structure. Compared with the array-based ArrayList, these are two completely different implementation technologies, which also determines that they will be suitable for completely different work scenarios.
     

7. What are the design patterns you know

 

  • In Java, it is generally believed that there are 23 design patterns, we don't need all of them, but several commonly used design patterns should be mastered. All the design patterns are listed below. I have listed the design patterns that need to be mastered separately, of course, the more you can master, the better.
  • Generally speaking, design patterns are divided into three categories:
  • There are five creational modes : factory method mode, abstract factory mode, singleton mode, builder mode, and prototype mode.
  • There are seven structural modes : adapter mode, decorator mode, agent mode, appearance mode, bridge mode, combination mode, and flyweight mode.
  • There are ten behavioral modes: strategy mode, template method mode, observer mode, iteration sub mode, responsibility chain mode, command mode, memo mode, state mode, visitor mode, intermediary mode, interpreter mode.
     

8. What is the difference between heap and stack

 

  • Explain the difference between heap and stack from the following aspects.

1. How to apply

  • stack: automatically allocated by the system. For example, declare a local variable int b in the function; the system automatically opens up space for b in the stack: the programmer needs to apply for it and specify the size. In the malloc function in C, it needs to be opened manually in the form of new Object() for Java.

2. System response after application

  • stack: As long as the remaining space of the stack is greater than the requested space, the system will provide memory for the program, otherwise an exception will be reported to indicate stack overflow.
     
  • Heap: First of all, you should know that the operating system has a linked list that records free memory addresses. When the system receives an application for a program, it will traverse the linked list to find the first heap node whose space is greater than the requested space, and then start the node from The free node list is deleted, and the space of the node is allocated to the program. In addition, since the size of the heap node found may not be exactly equal to the size of the application, the system will automatically put the extra part into the free list.

3. Restrictions on application size

  • stack: The stack is a data structure that extends to lower addresses, and is a contiguous area of ​​memory. This sentence means that the address of the top of the stack and the maximum capacity of the stack are pre-defined by the system. Under WINDOWS, the size of the stack is 2M (some say it is 1M, in short, it is a constant determined at compile time). If you apply When the space exceeds the remaining space of the stack, overflow will be prompted. Therefore, the space that can be obtained from the stack is smaller.
  • Heap: Heap is a data structure that extends to high addresses and is a discontinuous memory area. This is because the system uses a linked list to store free memory addresses, which are naturally discontinuous, and the traversal direction of the linked list is from low addresses to high addresses. The size of the heap is limited by the effective virtual memory in the computer system. It can be seen that
     

9. Since there is a GC mechanism, why is there still a memory leak 

 

  • In theory, Java has no memory leak problem because of the garbage collection mechanism (GC) (this is also an important reason why Java is widely used in server-side programming). However, in actual development, there may be useless but reachable objects. These objects cannot be reclaimed by the GC, which may also lead to memory leaks.
  • For example, the objects in hibernate's Session (- -level cache) are in a persistent state, and the garbage collector will not reclaim these objects. However, there may be useless garbage objects in these objects. If they are not closed in time (close) or empty (flush) )--Level caching may lead to memory leaks.
     

10 Why is there a GC mechanism in Java? 

  • Security considerations; - for security.
  • Reduce memory leak; - erase memory leak in some degree.
  • Reduce programmer workload. - Programmers don't worry about memory releasing.
     

11What memory needs to be recycled for Java GC

  • When the memory is running, the JVM will have a runtime data area to manage the memory. It mainly includes 5 parts: Program Counter Register, Virtual Machine Stack (VM Stack), Native Method Stack, and Method Area (Method Area). Heap (Heap). Among them, the program counter, virtual machine stack, and local method stack are the private memory space of each thread, which is born and died with the thread.
  • For example, how much memory is allocated in each stack frame in the stack is basically known when the class structure is determined. Therefore, the memory allocation and recovery of these three areas are determined, and there is no need to consider the problem of memory recovery.
  • However, the method area and the heap are different. The memory required by multiple implementation classes of an interface may be different. We only know which objects will be created during the running of the program. The allocation and recovery of this part of the memory are dynamic. GC The main concern is this part of memory. All in all, the memory that GC mainly reclaims is the method area and heap in the JVM;
     

12. When does Java GC collect garbage?

 

  • In interviews, we often encounter such a problem (in fact, the author has also encountered it): How to judge that a subject has died?
  • One answer that is easy to think of is: add a reference counter to an object. Whenever there is a reference to it, the counter value is increased by 1; when the reference is invalid, the counter value is decreased by 1. When the value of the counter is 0, the object will no longer be used, and it is judged to be dead. Is it simple and intuitive. However, it is a pity. This approach is wrong! Why is it wrong? In fact, using reference counting is indeed a good solution in most cases, and there are many cases in actual applications, but it cannot solve the object The problem of circular references between. For example, there is a field in object A that points to object B, and there is also a field in object B that points to object A, and in fact they are no longer used, but the value of the counter can never be 0, so it will not be Recycling, and then a memory leak occurred.
  • So, what should be the correct approach?
  • In Java, C# and other languages, the more mainstream method to determine that an object is dead is: Reachability Analysis. All generated objects are a subtree of the root called "GC Roots". Starting from GC Roots and searching downwards, the path that the search goes through is called Reference Chain. When an object reaches GC Roots without any reference chain, it is said that the object is unreachable (unreferenceable).
  • Whether it is a reference counter or reachability analysis, determining whether an object is alive is related to the reference! So, how to define the reference of the object?
  • We hope to give such a description: when there is enough memory space, it can be stored in memory; if the memory space is still very tight after garbage collection, these objects can be discarded. Therefore, according to different needs, the following four references are given. Depending on the type of reference, there will be different operations during GC recovery:
  • 1) Strong Reference: Object obj = new Object0; As long as the strong reference still exists, the GC will never reclaim the referenced object.
  • 2) Soft Reference: Description-some useful but not necessary objects. Before a memory overflow occurs in the system, these objects will be included in the recovery range for secondary recovery (that is, the system will have a memory overflow before they will be recovered.) The degree of weak reference (Weak Reference) is worse than soft reference. Be weaker. These objects can only survive until the next GC. When the GC is working, it will be recycled regardless of whether the memory is sufficient (that is, as long as the GC is performed, they will be recycled.) Phantom Reference: Whether an object has a phantom reference, it will not constitute its lifetime at all influences. What needs to be recycled in the method area are some obsolete constants and useless classes.
  • 1Recycling of abandoned constants. Look at the reference count here. If there is no object referencing the constant, you can safely recycle it.
  • 2. Recycling of useless classes. What is a useless class?
  • A. All instances of this class have been recycled. That is, there is no instance of this class in the Java heap;
  • B. The ClassLoader that loaded the class has been recycled;
  • C. The java.lang.Class object corresponding to this class is not referenced anywhere, and the methods of this class cannot be accessed through reflection anywhere.
  • all in all:
  • For objects in the heap, reachability analysis is mainly used to determine whether an object still has references. If the object does not have any references, it should be recycled. n According to our actual different needs for citations, it is divided into 4 citations, and the recycling mechanism for each citation is also different. For the constants and classes in the method area, when a constant does not have any object referencing it, it can be recycled. For the class, if it can be judged as
     

13. Talk about the native jdbc operation database process?

 

  1. The first step: Class.forName() loads the database connection driver;
  2. Step 2: DriverManager.getConnection() gets the data connection object;
  3. Step 3: Obtain sql session object according to SQL, there are two ways Statement. PreparedStatement;.
  4. The fourth step: execute SQL processing result set, if there is a parameter value before executing SQL, set the parameter value setXXX0;
  5. Step 5: Close the result set, close the session, and close the connection.
     

14. What should I use PreparedStatement? 

 

  • 1. PreparedStatement interface inherits Statement, PreparedStatement instance contains compiled SQL query, so its execution speed is faster than Statement object.
  • 2. As a subclass of Statement, PreparedStatement inherits all the functions of Statement. The three methods execute, executeQuery and executeUpdate have been changed so that they no longer need parameters
  • 3. In JDBC applications, do not use Statement at any time for the following reasons:
  • 1. The readability and maintainability of the code Statement needs to be continuously spliced, but PreparedStatement does not.
  • 2. PreparedStatement Improve performance as much as possible. DB has a caching mechanism, and the same prepared statement will not need to be compiled again if it is called again.
  • Third, the most important point is to greatly improve the security. Statement is easy to be injected by SQL, and the content passed in PreparedStatementc will not have any matching relationship with the SQL statement.

15.What is the mechanism of connection pool in relational database?

  • Prerequisite: Establish a buffer pool for the database connection.
  • 1: Obtain or create an available connection from the connection pool
  • 2: After use, return the connection to the connection pool
  • 3: Before the system shuts down, disconnect all connections and release the system resources occupied by the connections
  • 4: Ability to handle invalid connections and limit the total number of connections in the connection pool to not less than or not more than a certain limit value.
     

16. Can the key and value in the map be null?

 

  • The key and value of the HashMap object can be null.
  • The key. value of the HahTable object cannot be null.
  • And the key values ​​of the two cannot be repeated. If you add a key-value pair with the same key, the following value will automatically overwrite the previous value, but no error will be reported.
     

17. What are the reference types in Java? (Important)

  • Object references in Java are divided into four levels, the four levels from high to low are: strong reference, soft reference, weak reference and phantom reference.
  • Strong reference (StrongReference), not much to say about this, we write code every day using strong references. If an object is strongly referenced by someone, then the garbage collector will never reclaim it. When the memory space is insufficient, the Java virtual machine would rather throw an OutOfMemoryError error to make the program terminate abnormally, and would not solve the problem of insufficient memory by reclaiming objects with strong references at will.
  • Java objects are located in the heap. Objects in the heap include strongly reachable objects, soft reachable objects, weakly reachable objects, virtual reachable objects, and unreachable objects. The order of strength of application is strong, soft, weak, and weak. For what kind of reachable object the object belongs to is determined by its strongest reference. Next generation
     
  • The first line creates an object with the content "abc" in the heap, and establishes a strong reference from abc to the object, which is strongly reachable.
  • The second and third lines respectively establish soft and weak references to the objects in the heap. At this time, there are already 3 references to the abc object in the heap. Obviously, the abc object is still strongly reachable at this time.
  • After the fourth line, the objects in the heap are no longer strongly reachable, and become soft reachable.
  • The fifth line becomes weakly accessible after execution. Soft Reference (SoftReference)
  • If an object only has soft references, then if the memory space is sufficient, the garbage collector will not reclaim it. If the memory space is insufficient, the memory of these objects will be reclaimed. As long as the garbage collector does not reclaim it, the object can be used by the program. Soft references can be used to implement memory-sensitive caches.
  • The soft reference can be used in conjunction with a reference queue (ReferenceQueue). If the object referenced by the soft reference is garbage collected, the Java virtual machine will add the soft reference to the reference queue associated with it. Soft references are mainly used for memory-sensitive caches. Before the jvm reports that the memory is insufficient, all soft references are cleared, so that gc may collect softly accessible objects, which may solve the memory problem and avoid memory overflow. When will be collected depends on the gc algorithm and the size of the available memory when gc is running.
  • When gc decides to collect soft references, perform the following process, taking the above softRef as an example:
  • 1 First, set the referent (abc) of softRef to nll, and then refer to the new String (" abc) object in the heap.
  • 2 Set the new String (" abc') object in the heap to be finalizable.
  • 3 When the finalize0 method of the new String("abc") object in the heap is executed and the memory occupied by the object is released, softRef is added to its ReferenceQueue (if any).
  • Note: Soft references and weak references to ReferenceQueue can be dispensed with, but phantom references must be present.
  • The object pointed to by the Soft Reference will not be cleared even if there is no Direct Reference. It will not be cleared until the JVM memory is insufficient and there is no Direct Reference. SoftReference is used to design object-cache. In this way, SoftReference can not only cache the object, but also will not cause out of memory errors (OutOfMemoryError).
  • Weak Reference (WeakReference)
  • If an object has only weak references, then the class is a dispensable object, because as long as the object is scanned by gc, it will be killed at any time. The difference between weak reference and soft reference is that only objects with weak references have a shorter life cycle. In the process of the garbage collector thread scanning the memory area under its jurisdiction, once an object with only weak references is found, its memory will be reclaimed regardless of whether the current memory space is sufficient. Since the garbage collector is-a thread with a very low priority, so it is not always-will quickly find those objects that only have weak references.
  • A weak reference can be used in conjunction with a reference queue (ReferenceQueue). If the object used by the weak reference |uses the reference| is garbage collected, the Java virtual machine will add the weak reference to the reference queue associated with it.
     
  • PhantomReference
  • As the name suggests, "virtual reference" is nothing but a virtual reference. Unlike other types of references, virtual reference does not determine the life cycle of an object. If-an object holds only phantom references, then it is the same as without any references-it may be garbage collected at any time. Phantom references are mainly used to track the activities of objects being garbage collected.
  • One difference between phantom reference and soft reference and weak reference is: phantom reference must be used in conjunction with reference queue (ReferenceQueue). When the garbage collector is ready to reclaim an object, if it finds that it has a phantom reference, it will add the phantom reference to the reference queue associated with it before reclaiming the object's memory. The process can determine whether the referenced object will be garbage collected by judging whether a virtual reference has been added to the reference queue.
  • If the program finds that a phantom reference has been added to the reference queue, it can take necessary actions before the memory of the referenced object is reclaimed. After the virtual reference is established, the result returned by the get method is always null. Through the source code, you will find that the virtual reference will write the referenced object into the referent, but the return result of the get method is null. Let's take a look at the process of interacting with gc and then talk about his role.
  • 1 Don't set referent to null, directly set the new String (" abc') object in the heap to be finalizable (finalizable).
  • 2 Different from soft references and weak references, first add the PhantomRefrence object to its ReferenceQueue. Then release the phantom reachable object.
     

Guess you like

Origin blog.csdn.net/c202003/article/details/107396186