First, the basic part
1, Java three features, what are the use, how to achieve, where used?
Encapsulation, inheritance, polymorphism.
Encapsulation: Hides the attributes and implementation details of an object and provides only public access.
Benefits: Isolation of change, ease of use, increased reuse, and improved security.
Principle of encapsulation: Hide content that doesn’t need to be made public. Hide attributes and provide public access to them.
Application:
1, the private keyword: is a permission modifier. Privatized members used to modify members (member variables and member functions) are valid only in this class.
Common one: privatize a member variable, provide the corresponding set externally, and access it with the GET method. Improve security of data access.
Construct code block and constructor (Construct) :
Constructor: used to initialize the object, is given the corresponding object to initialize, it has targeted, one of the functions.
Features: The name of this function is the same as the name of its class. There is no need to define a return value type. This function has no concrete return value.
1. The function of the constructor is compared with the function of the constructor:
(1) The constructor code block is used to uniformly initialize all objects, run as soon as they are created and take precedence over constructors, for example, all babies cry when they are born.
(2) Constructor: initializes the corresponding object (new). Construct code block format: {construct code block; }
Note: The brace that constructs the code block must be at the location of the member.
Type of code block:
(1) Construct code blocks: often used in work.
(2) Local code blocks: the curly braces are inside the method, and it basically makes no difference whether it is written or not, which is rarely used in real development. Its purpose is to shorten the life cycle of local variables and save a little memory.
(3) Static code block: code block with static modifier.
Notes:
(1) When compiling a Java source file, the Java compiler puts the declaration of member variables at the front of a class.
(2) The initialization of a member variable is actually done in the constructor.
(3) Once compiled by the Java compiler, the code that builds the code block is moved to the constructor and executed before the constructor, and the code in the constructor is executed last.
(4) The display initialization of member variables and the construction of code blocks are executed in the order of the current code.
Inheritance: Inheritance is one of the most prominent features of object orientation. Inheritance is the derivation of a new class from an existing class, which can absorb the data attributes and behavior of the existing class and extend the new capabilities.
In JAVA, an inherited class is called a parent class or superclass, and a class that inherits from a parent class is called a subclass or derivedclass. Thus, a subclass is a purpose-built version of the parent class that inherits all instance variables and methods defined in the parent class and adds unique elements.
Application:
Keyword: extends. Use inheritance – write a parent class – write a subclass, inherit a parent class
class Animal {
// Public attributes and methods
}
class Chicken extends Animal{
Subclass-specific attributes and methods
}
class Duck extends Animal {
}
Class Chicken extends Animal{} Class Chicken extends Animal{} Class Chicken extends Animal{} Under the inheritance relationship, the Chicken class will have all the non-private methods and attributes of the Animal class. The Chicken class can also have its own methods and attributes. Declare the Animal class, and when instantiating the Chicken class, the Chicken class will automatically go up to Animal.
Polymorphism: In object-oriented languages, polymorphism means that a method can have multiple implementations, i.e., “one definition, many implementations.” With polymorphism, extensible systems can be designed and implemented as long as the new classes are also in the inheritance hierarchy. The new classes make little or no changes to the general parts of the program. The polymorphism of class is the polymorphism of method, which mainly includes method overloading and method covering. Overload: Method overload means that multiple methods in the same class can have the same name but must have different argument lists. Overloading is represented by polymorphism of methods in the same class.
Override: A method override is when a subclass defines a method of the same name in its parent class. Rewriting is represented by method polymorphism between parent and subclass.
Object type conversion: Data of primitive types can be converted, automatically converted when the conversion type is high, and cast when the conversion type is low. Object types also allow conversions, which are limited to one branch of the Java class hierarchy diagram, between the parent and subclasses. The branch that is closer to the Object is up, and the branch that is farther from the Object is down. Thus, Object type conversion can be divided into “upward transformation” and “downward transformation”. (A parent class reference points to a subclass object.) Downcast: Only for base class object references that point to subclass objects.
Upcast: A subclass object becomes a parent object. Here the superclass object can be an interface.
2. What is the difference between HashMap, Hashtable and ConcurrentHashMap?
HashTable
The basic array + linked list implementation, neither key nor value can be null, thread-safe, thread-safe way is to lock the entire HashTable when modifying data, low efficiency, ConcurrentHashMap has made relevant optimization
The initial size is 11. Expand the capacity: newsize = olesize*2+1
Index = (hash & 0x7FFFFFFF) % tab.length
HashMap
Bottom array + linked list implementation, can store NULL keys and NULL values, thread is not safe
Newsize = oldsize*2, size must be 2 to the NTH power
Each time the Map is expanded, the elements in the original array are recalculated and inserted again
It is possible to determine whether to expand the capacity after the element is inserted. (Invalid expansion will occur if the element is not inserted again.)
When the total number of elements in the Map exceeds 75% of the entries in the array, the expansion operation is triggered. To reduce the length of the linked list, the elements are distributed more evenly
Index = hash & (tab.length — 1)
The initial value of the HashMap also takes into account the load factor:
Hash collision: The hash values of several keys modulo the size of the array and fall on the same index form an Entry chain. The search for keys requires an equals() comparison over each element in the Entry chain.
Load factor: To reduce the probability of hash collisions, expansion is triggered by default when the key-value pairs in the HashMap reach 75% of the array size. Therefore, if the estimated capacity is 100, you need to set the array size of 100/0.75 = 134.
Space for time: If you want to speed up the Key search time, you can further reduce the loading factor and increase the initial size to reduce the probability of hash conflicts.
Both HashMap and Hashtable use hash algorithms to determine the storage of their elements, so the hash table of a HashMap and Hashtable contains the following attributes:
Capacity: indicates the number of buckets in the hash table
Initial capacity: The number of buckets at which the hash table is created. HashMap allows you to specify initial capacity in the constructor
Size: indicates the number of records in the current hash table
Load Factor: The load factor is equal to size/ Capacity. A load factor of 0 represents an empty hash table, 0.5 represents a half-full hash table, and so on. A lightly loaded hash table has the characteristics of low conflict, good insertion and query (but slower Iterator iterating over elements)
In addition, the hash table also has a load limit, which is a value from 0 to 1. The load limit determines the maximum amount of the hash table can be filled. When the hash table’s load factor reaches a specified “load limit,” the hash table automatically doubles the capacity (number of buckets) and redistributes the original objects into new buckets. This is called rehashing.
The constructors of HashMap and Hashtable allow you to specify a load limit. The default “load limit” for HashMap and Hashtable is 0.75, indicating that rehashing can occur when three-quarters of the hash table is already full.
The default value of “load limit” (0.75) is a compromise on the cost of time and space:
A high “load limit” reduces the memory footprint of hash tables, but increases the time overhead of querying data, which is the most frequent operation (both get() and PUT () of a HashMap use queries)
A low “load limit” improves the performance of the query data, but increases the memory overhead of the hash table
The programmer can adjust the load limit value according to the actual situation. ConcurrentHashMap
The bottom layer of the segmented array + linked list implementation, thread safety
By dividing the entire Map into N segments, this provides the same thread-safety but an n-fold increase in efficiency, which is a 16-fold increase by default. (The read operation is unlocked, and since the HashEntry value variable is volatile, the latest value is guaranteed to be read.)
Synchronized of Hashtable is for the whole Hashtable, that is, lock the whole table at a time and let the thread monopolizes it. ConcurrentHashMap allows multiple modification operations to be carried out concurrently. The key is the use of lock separation technology
Some methods that span segments, such as size() and containsValue(), may need to lock the entire table instead of just one segment, which requires locking all segments sequentially and releasing all segments sequentially when done
Capacity expansion: Capacity expansion within a segment (If the number of elements in a segment exceeds 75% of the length of the corresponding Entry array, capacity expansion will not be performed on the entire Map). Check whether the Map needs to be expanded before insertion to avoid invalid capacity expansion
Both Hashtable and HashMap implement the Map interface, but the implementation of Hashtable is based on the Dictionary abstract class. Java5 provides ConcurrentHashMap, which is an alternative to HashTable and is more extensible than HashTable.
HashMap is based on the idea of hash, which implements data reading and writing. When we pass the key-value pair to the put() method, it calls the hashCode() method of the key object to compute the hashCode, and then finds the bucket location to store the value object. When an object is retrieved, the correct key-value pair is found through the equals() method of the key object, and the value object is returned. A HashMap uses a linked list to solve collisions, and when a collision occurs, the object is stored in the next node in the list. HashMap stores key-value pair objects in each linked list node. When two different key objects have the same Hashcode, they are stored in a linked list at the same bucket location, and the key-value pairs can be found using equals() on the key objects. If the list size exceeds the threshold (TREEIFY_THRESHOLD,8), the list is transformed to a tree structure.
In a HashMap, NULL can be used as a key. There is only one such key, but there can be one or more keys with a value of NULL. When the get() method returns a null value, it can indicate that the key does not exist in the HashMap, or that the value corresponding to the key is null. Therefore, it is not possible to use the get() method to determine whether a HashMap contains a key. Instead, it is possible to use the containsKey() method to determine whether a HashMap contains a key. In a Hashtable, neither key nor value can be null.
Hashtable is thread-safe, its methods are synchronous and can be used directly in a multithreaded environment. HashMap, on the other hand, is not thread-safe and requires manual synchronization in a multi-threaded environment.
Another difference between Hashtable and HashMap is that a HashMap’s Iterator is a fail-fast Iterator, whereas a Hashtable’s Enumerator is not a fail-fast Iterator. So when there are other threads to change the structure of a HashMap (add or remove elements), will throw ConcurrentModificationException, But the iterator itself the remove () method removes elements will not throw ConcurrentModificationException. But this is not a guaranteed behavior; it depends on the JVM.
Let’s start with a simple class diagram:ConcurrentHashMap has one more class Segment than HashMap. Segment is a reentrant lock.
ConcurrentHashMap uses lock fragmentation to keep threads safe.
Lock segmentation technology: firstly, the data is divided into sections for storage, and then each section of data is equipped with a lock. When a thread uses the lock to access one section of data, the data of other sections can also be accessed by other threads.
ConcurrentHashMap provides a different locking mechanism than Hashtable and SynchronizedMap. The locking mechanism used in Hashtable locks the entire hash table at once, so that only one thread can operate on it at a time; ConcurrentHashMap locks one bucket at a time.
ConcurrentHashMap Divides the hash table into 16 buckets by default. Common operations such as GET, PUT, and remove lock only the buckets that are currently used. As a result, a single thread can now be entered by 16 writers at the same time, and the concurrency improvement is noticeable.
One thing to note here: after JDK1.8, if the hashMap is longer than 8 and the node array is longer than 64, all nodes in the list are turned into red-black trees.
Second, the framework
1, SpringBoot commonly used annotations, what is the role?
1.1, @SpringBootApplication, after creating the SpringBoot project will be added to the main class by default, can be regarded as @Configuration, @EnableAutoConfiguration, @ComponentScan annotation collection;
1.2. @enableAutoConfiguration: Enable the automatic configuration mechanism of SpringBoot;
@ComponentScan: Scans beans annotated by @Component (@Service,@Controller). By default, annotations scan all classes in the package in which this class belongs.
1.4, @Configuration: Allows registering additional beans or importing additional Configuration classes in the Spring context.
What are the common annotations and functions of the Spring framework?
Spring Bean related:
2.1. @autoWired: Automatically import objects into a class;
2.2. We typically use the @AutoWired annotation to have the Spring container automatically assemble beans for us. To identify a class as a bean that can be used with the @AutoWired annotation auto-assembly, use the following annotation:
Component: Generic annotation to mark any class as a Spring Component. If a Bean does not know which layer it belongs to, it can be annotated using the @Component annotation.
@repository: Corresponds to the persistence layer (Dao layer), which is used for database-related operations.
@service: corresponds to the Service layer, which involves complex logic and requires the Dao layer.
@Controller: corresponding to the Spring MVC control layer, the main user accepts the user request and calls the Service layer to return data to the front-end page.
2.3, @restcontroller is the @controller and @responsebody combination, indicating that this is a Controller bean, and that it is the return value of the function directly into the HTTP ResponseBody, is a REST style Controller;
2.4. @scope: Declares the Scope of the Spring Bean.
There are four common Spring Bean scopes:
Singleton: A unique bean instance. Beans in Spring are singleton by default.
Prototype: Each request creates a new bean instance.
Request: Each HTTP request generates a new bean that is valid only within the current HTTP Request.
Session: Each HTTP request generates a new bean that is valid only for the current HTTP session.
2.5. Configuration: Normally used to declare Configuration classes. You can use the @Component annotation instead, but using the Configuration annotation to declare Configuration classes is more semantic.
Front and back end values:
2.6 @pathVariable is used to obtain path parameters, and @requestParam is used to obtain query parameters;
2.7, @ RequestBody: It is used to read the body part of the Request (POST,PUT,DELETE,GET) and the content-type is application/ JSON format. After receiving the data, it will automatically bind the data to the Java object.
Reading configuration information:
2.8. @value: Reads simple configuration information.
2.9, @configurationProperties: Reads the configuration information and binds it to the bean.
Parameter verification:
The annotated @notempty string cannot be null or null;
@null Annotated elements must be Null;
2.12. @assertTrue Annotated elements must be true;
2.13. @assertFalse Annotated elements must be false;
2.14. @email Annotated elements must be in the Email format.
Global handle Controller layer exception:
2.15. @controllerAdvice: Annotation defines the global exception handling class.
2.16 @ExceptionHandler: Annotation declares exception handling method.
JPA related:
2.17, @entity declares that a class corresponds to a database Entity;
2.18. @id: Declare a primary key for a field;
2.19, @column declare Column;
2.20. @TRANSIENT: declare the fields that do not need to be mapped to the database, and do not need to be saved into the database when saving;
2.21. @lob: Declare a field as a large field;
Transactional: used on methods that open a transaction;
2.23, @jsonignoreProperties: used on a class to filter out specific fields without returning or parsing;
2.24. @jsonFormat is generally used to format JSON data.
2.25. @ActiveProfiles typically works on test classes to declare valid Spring profiles.
What is the difference between a GET request and a POST request?
Here we list the common request types in 5.
GET: Requests to GET a specific resource from the server. For example: GET /users (GET all students)
POST: Creates a new resource on the server. For example: POST /users (create students)
PUT: Updates the resource on the server (the client provides the updated entire resource). For example: PUT /users/12 (update student number 12)
DELETE: Deletes a specific resource from the server. For example: DELETE /users/12 (DELETE student number 12)
PATCH: Updates resources on the server (the client provides the changed properties, which can be regarded as partial updates). It is rarely used, so there are no examples here.
Due to the large capacity, I also need to deal with daily work. Therefore, the interview questions will be sorted out in batches, I hope you can understand. Inadequate place can leave a message to discuss oh!