[Set 2] Java interview questions

Second set:

1. JavaScript front-end development

1. What does the following code output?

var y = 1;
if(function f(){
    
    }){
    
    
    y += typeof f;
}
console.log(y);

The correct answer should be 1undefined.
The evaluation of if statements in JavaScript actually uses the eval function. eval(function f(){}) returns function f(){}, which is true.
Next we can transform the code into its equivalent code.

var k = 1;
if (1) {
    
    
    eval(function foo(){
    
    });
    k += typeof foo;
 }
console.log(k);

The output of the above code is actually 1undefined. Why that? We can get the answer by looking at the eval() documentation

This method only accepts raw strings as parameters. If the string parameter is not a raw string, the method will return unchanged.

It just so happens that the return value of the function f(){} statement is undefined , so everything makes sense.
Note that the code above is different from the code below.

var k = 1;
if (1) {
    
    
    function foo(){
    
    };
    k += typeof foo;
 }
console.log(k); // output 1function 

2. Write a caNum function. You can think of the parameters as follows. The method of use is as follows:

Console.log(caNum(2)(3)(4)); //输出:24
Console.log(caNum(4)(3)(4)); //输出:48

The most common implementation version:

var multiply = function () {
    
    
  var a = 1;
  for (let i = 0; i < arguments.length; i++) {
    
    
    a = a * arguments[i];
  }
  return a;
}
console.log('11:',multiply(1,2,3,4)); // 输出:24

If you want to know about the optimized version, link: https://blog.csdn.net/qq_37268201/article/details/113262983

3. Write a function to use JQuery to determine whether the variable obj is an array.

var arr= [1,1,1,1]
var a = '2323'
var b =  {
    
    name:'xiao',age:12}
var n = 1

1. instanceof
The instanceof operator is used to check whether the prototype attribute of the constructor appears anywhere in the object's prototype chain and returns a Boolean value.
Note that the prototype attribute can be modified, so it does not necessarily mean that it will always be true if it is initially judged to be true.

console.log('方法1',arr instanceof Array); //如果是数组 打印结果为 true

2.
The constructor attribute constructor of the constructor instance points to the constructor, so you can also determine whether it is an array through the constructor attribute.
This kind of judgment will also have problems with multiple global environments, causing the same problems as instanceof.

console.log('方法2',arr.constructor === Array);//true

3. Array.isArray() is the most recommended method
. It can also be judged accurately, but there is a problem. Array.isArray() was proposed in ES5, which means that there may be situations where this method is not supported before ES5.

console.log('方法3',Array.isArray(arr)); //true

function isArray(obj){
    
    
 return $.isArray(obj)
}//JQuery isArray 的实现其实就是方法5

4.
When typeof uses this method to judge an array, the printed result is object (the disadvantage is that if the data type is a reference data type, it can only return Object)

The return results of this method are only the following: Number, String, undefined, Bollean, Object, Function

console.log('方法4',typeof n); //number
console.log('方法4',typeof(b)) //object

5 Object.prototype.toSrtring.call()
When using this method to determine other data types, one thing to note is that in IE8 and below, undefined and null are both Object, and IE9 and above are [object Undefined] and [object Null].

console.log(Object.prototype.toString.call(arr).indexOf('Array') !== -1); //true
console.log(Object.prototype.toString.call(arr) === '[object Array]');    //true

function isArray(obj){
    
    
 return Object.prototype.toString.call( obj ) === '[object Array]'; 
} //这里使用call来使 toString 中 this 指向 obj。进而完成判断

Reference link: https://blog.csdn.net/qq_43399210/article/details/111403146

4. The following code throws an exception when running. Please correct the code to ensure it can be executed.

var foo = function bar(){
    
    return 12;};
typeof bar();

The output is that an exception is thrown and bar is not defined. If you want the code to run normally, you need to modify the code like this:

var bar = function(){
    
     return 12; };
typeof bar();

或者是

function bar(){
    
     return 12; };
typeof bar();

2. Java back-end development:

1. How to serialize objects in Java and when serialization is needed;

Only objects of classes that implement the Serializable or Externalizable interface can be serialized into byte sequences. (If not, an exception will be thrown.)
On the one hand, the sender needs to convert the Java object into a byte sequence and then transmit it on the network; on the other hand, the receiver needs to recover the Java object from the byte sequence.

Serialization: The process of converting Java objects into byte sequences (binary).
Deserialization: The process of restoring a sequence of bytes into a Java object.

Note: Serialization is the process of converting object state into a format that can be maintained or transmitted. Deserialization converts a stream into an object. These two processes combine to easily store and transfer data. JSON is the format used for interface data exchange. The core function is to save and reconstruct the object state

Serialization and deserialization generally boil down to the following points:

  • Permanently save the byte sequence of the object to the hard disk, usually in a file; (persistent object) converts the object into a byte stream and stores it on the hard disk. When the JVM is shut down, the byte stream will still be on the hard disk. Wait silently for the next start of the JVM, deserialize the serialized object into the original object, and the serialized binary sequence can reduce storage space

  • A sequence of bytes that transmits an object over the network. (Network transfer object)

  • Pass objects between processes through serialization;

2. List the commonly used Map collections and briefly describe the difference between HashMap and HashTable;

Map mapping: unordered, unique keys, non-unique values
Insert image description here

HashMap: Hash map/dictionary, unordered dictionary, key-value pair data, key is unique, both Key and Value can be null
Hashtable: similar to HashMap, it is a thread-safe version of HashMap. It supports thread synchronization, that is, any Only one thread can write to Hashtable at a time, so Hashtale is slower when writing. It inherits from the Dictionary class. The difference is that it does not allow the recorded key or value to be null, and is less efficient.
TreeMap: Key->value fusion implemented by red-black tree, which can be sorted. Red-black tree is a self-balancing binary search tree.
LinkedHashMap: Linked list mapping/dictionary, inherits all the characteristics of hashmap, and at the same time implements the characteristics of doubly linked list, retaining the insertion order of elements.
ConcurrentHashMap: thread-safe and lock-separated. ConcurrentHashMap uses segments internally to represent these different parts. Each segment is actually a small hash table, and they have their own locks. Multiple modification operations can occur concurrently as long as they occur on different segments.

The difference between HashMap and HashTable:

  • HashMap removes the contains method of HashTable, but adds containsValue() and containsKey() methods.
  • HashTable is synchronous and thread-safe; HashMap is asynchronous and is more efficient than hashTable.
  • HashMap allows empty key values, but hashTable does not.

3. Write code: Java Map traversal method.

Map content: {"name":"Zhang Moumou", "age": "30", "sex": "male", "code": "3010"}

1. Using entrySet traversal in a for loop, you can also get the key and value at the same time, which is the most commonly used.

Map <String,String>map = new HashMap<String,String>();
map.put("熊大", "棕色");
map.put("熊二", "黄色");
for(Map.Entry<String, String> entry : map.entrySet()){
    
    
    String mapKey = entry.getKey();
    String mapValue = entry.getValue();
    System.out.println(mapKey+":"+mapValue);
}

2. Use map.keySet() in the for loop to traverse the key to obtain a single value through map.get(key), or use map.values() to traverse to obtain values. This method is generally suitable
for when you only need the key or value in the map. Using it is better in performance than using entrySet;

Map <String,String>map = new HashMap<String,String>();
map.put("熊大", "棕色");
map.put("熊二", "黄色");
//key
for(String key : map.keySet()){
    
    
    System.out.println(key);
}
//value
for(String value : map.values()){
    
    
    System.out.println(value);
}
System.out.println("通过map.keyset进行遍历key和value");

for (String key:map.keySet()){
    
    

    System.out.println("key= "+key+" and value= "+map.get(key));

}

3. Traversal through Iterator
When traversing using Iterator: When using foreach to traverse the map, if you change its size, an error will be reported, but if you just delete elements, you can use the remove method of Iterator to delete elements.

Iterator<Entry<String, String>> entries = map.entrySet().iterator();//用迭代器的时候注意:next()方法在同一循环中不能出现俩次!
//否则会抛出NoSuchElementException异常。
while(entries.hasNext()){
    
    
    Entry<String, String> entry = entries.next();
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key+":"+value);
}

4. Traversing the value through the key (that is, the second way to traverse the key + the way to get the value) is
relatively inefficient because getting the value from the key itself is a time-consuming operation and is not recommended;

for(String key : map.keySet()){
    
    
    String value = map.get(key);
    System.out.println(key+":"+value);
}

Some conclusions:
If you only want to get keys or values, it is recommended to use keySet or values.
If you need both key and value, it is recommended to use entrySet.
If you need to delete elements during the traversal process, it is recommended to use Iterator
. If you need to add elements during the traversal process, you can create a new temporary one. The map stores the newly added elements. After the traversal is completed, the temporary map is placed into the original map.

Map traversal reference link: https://blog.csdn.net/qq_44750696/article/details/112254719

4. Create an instance of the com.weavercsd.po.UseerInfo object through "reflection".

There are two ways to create objects through reflection:
1. Use the newInstance method of the Class object to create a class instance corresponding to the Class object (the class corresponding to the Class object has a default empty constructor)

Class clazz = Class.forName("com.weavercsd.po.UseerInfo");
Person person = (Person) clazz.newInstance();

2. Use the newInstance method of the Constructor object to create a class instance corresponding to the Class object.
This method has two steps:
1. Obtain the specified Constructor object through the Class object.
2. Call the newInstance method of the Constructor object to create a class instance corresponding to the Class object.
This method can be selected. Constructor creates instance

Class clazz = Class.forName("com.weavercsd.po.UseerInfo");
Constructor declaredConstructor = clazz.getDeclaredConstructor(Integer.class, String.class, Integer.class, String.class);
Person person = (Person) declaredConstructor.newInstance(1, "张三", 30, "男");

Use the newInstance method of the Class object:

@Data
public class Person {
    
    

    private Integer id;
    private String name;
    private Integer age;
    private Integer sex;
}
public class TestReflectCreateObj {
    
    
    public static void main(String[] args) {
    
    
        Class clazz = null;
        try{
    
    
            clazz = Class.forName("com.kevin.base.reflect.Person");
            Person person = (Person) clazz.newInstance();
            System.out.println(person);
        }catch (ClassNotFoundException e){
    
    
            e.printStackTrace();
        } catch (InstantiationException e) {
    
    
            e.printStackTrace();
        } catch (IllegalAccessException e) {
    
    
            e.printStackTrace();
        }
    }
}

 执行结果:
 Person(id=null, name=null, age=null, sex=null)

Use the Constructor object newInstance method:

@Data
@AllArgsConstructor
public class Person {
    
    

    private Integer id;
    private String name;
    private Integer age;
    private String sex;
}

public class TestReflectCreateObj {
    
    
    public static void main(String[] args) {
    
    
        Class clazz = null;
        try{
    
    
            //1.获取Person类的Class对象
            clazz = Class.forName("com.kevin.base.reflect.Person");
            //2.获取构造方法并创建对象
            Constructor declaredConstructor = clazz.getDeclaredConstructor(Integer.class, String.class, Integer.class, String.class);
            //3.根据构造方法创建对象并设置属性
            Person person = (Person) declaredConstructor.newInstance(1, "张三", 30, "男");
            System.out.println(person);
        }catch (Exception e){
    
    
            e.printStackTrace();
        }
    }
}

执行结果:
Person(id=1, name=张三, age=30, sex=)

5. What is the difference between XML and JSON, and what are the parsing methods?

Difference:
XML is mainly composed of element, attribute and element content. JSON is mainly composed of object, array, string, number, boolean (true/false) and null.
To represent an object (referring to a collection of name-value pairs), XML may initially use element as the object, and each key-value pair is represented by an attribute.
XML needs to choose how to handle line breaks of element content, but JSON string does not need to make this choice.
XML only has text and no preset number format, while JSON has a clear number format, which is also safe in locale.
There is no big problem with XML mapping arrays, except that array element tags are repetitive and redundant. JSON is easier to read.
JSON's true/false/null can also be easily unified into the corresponding semantics of general programming languages.
XML documents can be attached with DTD, Schema, and a bunch of specifications such as XPath. Using custom XML elements or attributes, you can easily attach various constraints and associated additional information to the data. From the perspective of data expression ability, XML is stronger than Json, but many scenarios do not require such complex and heavyweight things. The lightweight and flexible Json is very popular.

XML: In JAVA, you can use DOM, SAX, DOM4J or JDOM to parse
DOM to form a tree structure, which is intuitive and easy to understand, and the code is easier to write. During the parsing process, the tree structure is retained in memory for easy modification. When the XML file is large, it consumes a lot of memory, which can easily affect the parsing performance and cause memory overflow.
SAX uses an event-driven model, which consumes relatively little memory. It is suitable for when you only need to process data in xmI. But it is not easy to code, and it is difficult to access multiple different data in the same xml at the same time.
DOM4J is a very, very excellent Java XML API that reads the entire document and then parses it. It has the characteristics of excellent performance, powerful functions and extreme ease of use. It is also an open source software.
JDOM is a tree-based Java API for processing XML. It loads the tree in memory and has no backward compatibility restrictions. Therefore, it is simpler, faster and has fewer defects than DOM. It has the JAVA rules of SAX, but it cannot handle documents larger than the memory, JDOM said
. XML document logical model. There is no guarantee that every byte is actually transformed. No actual models of DTDs and schemas are provided for instance documents. The corresponding traversal package in the DOM is not supported.
JSON: JAVA Use FastJSON, Gson or Jackson to parse
Fastjson is a high-performance JSON processor written in Java language and developed by Alibaba. No dependencies, no need for extra jars, and can run directly on the JDK. FastJson uses an original algorithm to increase the speed of parse to the extreme, surpassing all json libraries.
GsonIt is currently the most versatile Json parsing artifact. Gson was originally developed by Google in response to Google's internal needs. However, since the first version was publicly released in May 2008, it has been used by many companies or users. The application of Gson mainly consists of two conversion functions: toJson and fromJson. It has no dependencies and does not require additional jars. It can run directly on the JDK.
Jackson relies on fewer jar packages, is simple and easy to use, and has relatively high performance. Moreover, the Jackson community is relatively active and the update speed is relatively fast. Jackson will have problems with complex types of json conversion beans, and there will be problems with the conversion of some collections Map and List. Jackson converts complex type beans to Json, and the converted json format is not the standard Json format. json-lib is the earliest and most widely used json parsing tool. The disadvantage of json-lib is that it relies on many third-party packages.

XML
extensible markup language is an important tool for Internet data transmission. It can span any platform on the Internet and is not restricted by programming languages ​​and operating systems.

Features:

  • 1.xml has nothing to do with the operating system and the development platform that becomes the language
  • 2. Realize data interaction between different systems

effect:

  1. Configure application
  2. Data interaction
  3. Ajax cornerstone

rule:

  1. There must be an xml declaration statement
  2. There must be exactly one root element
  3. Tags are case sensitive
  4. Use double quotes for attribute values
  5. Tags appear in pairs
  6. Empty tag close
  7. Elements are nested correctly

JSON
is a data exchange format. The full name of json is JavaScript Object Notation, which means object notation. It is a text-based, language-independent lightweight data exchange format.

Features:

  1. JSON is plain text.
  2. JSON is self-descriptive and easy to read.
  3. JSON has a hierarchical structure (there are values ​​within values).
  4. JSON can be parsed via JavaScript.
  5. JSON data can be transferred using AJAX.

The difference between JSON and XML:
6. In terms of data volume, compared to XML, JSON has a smaller data volume and faster transmission.
7. In terms of data interaction, JSON interacts with JavaScript more conveniently, easier to parse and process, and has better data interaction.
8 . In terms of data description, JSON is less descriptive than xml.
9. In terms of transmission speed, JSON is much faster than xml.

Advantages and disadvantages of JSON and xml:

  1. JSON is lightweight, simple to parse, and more client-friendly
  2. xml is more cumbersome. It is parsed into DOM numbers and traversed nodes to obtain data. The advantages are clear structure and good scalability.

6. Briefly describe the Restful architecture and list the most commonly used HTTP request methods supported by Rest.

REST is an architectural design guideline that all web applications should abide by. It uses URI to locate resources and HTTP (GET, POST, DELETE, PUT) to describe operations.
The full name of REST is Representational State Transfer, which in Chinese means representation (Editor's note: usually translated as representation) state transfer.
RESTful is an architecture for URIs . Using RESTful-style URIs can make URIs more readable. The code is cleaner and more logical.
First of all, you must understand that the RESTful architecture is resource-oriented. Each URI identifies a resource. When users or programmers use URIs, they are actually manipulating resources.
Therefore, URIs should always be designed around resources. (You can bring the primary key of the resource in the URI, the version number in the URI, use / to distinguish the hierarchical relationship of resources, and use ? to filter resources)

The biggest features of REST are: resources (database information that needs to be queried, etc.), unified interface (get, post, delete, put), URI (URI can be regarded as both the address of the resource and the address of the resource. Name, each URI corresponds to a specific resource), stateless (all resources can be located through URI, and this positioning has nothing to do with other resources, and will not change due to changes in other resources).
EX: Let’s give a simple example to explain the difference between stateful and stateless. For example, if you query the salary of an employee, you need to log in to the system, enter the salary query page, and perform relevant operations to obtain the salary. This situation is stateful, because each step of querying the salary depends on the previous operation. One-step operation, as long as the previous operation is unsuccessful, subsequent operations cannot be executed; if you enter a URL to get the salary of the specified employee, this situation is stateless, because obtaining the salary does not depend on other resources or states, and this In this case, employee salary is a resource, corresponding to a URL, and the resource can be obtained through the GET method in HTTP. This is a typical RESTful style. REST follows the principle of stateless communication. This does not mean that client applications cannot have state. It means that the server should not retain the client's state.

RESTful architecture:
  (1) Each URI represents a resource;
  (2) A certain presentation layer of this resource is transferred between the client and the server;
  (3) The client uses four HTTP verbs to access server-side resources. Operation to achieve "presentation layer state transformation".

2. The client's HTTP request methods are generally divided into four types: GET, POST, PUT, DELETE, PATCH, HEAD and OPTIONS.
GET is to obtain resources, POST is to create resources (can also be used to update resources), PUT is to update resources, and DELETE is to delete resources. GET
: Get resources. When the client uses the GET method to request the server, the server will return the URI associated with the request. The representation of the resource. The GET method should not change the state of the resource on the server. GET simply accesses and views resources. GET operations are safe.

GET /users HTTP/1.1
Host: api.example.com

In the above example, the client uses the GET method to obtain all user information and returns the response data in JSON or XML format.
POST: Create resources (can also be used to update resources). When the client uses the POST method to send a request to the server, the server will create a new resource and return the URI of the resource. The operation is not safe. Each request will create resources. When we make multiple POST requests, the result is that multiple resources are created.
Another thing to note is that the creation operation can use POST or PUT. The difference is that POST operates on a collection resource (/uri), while the PUT operation operates on a specific resource (/ uri/xxx), to put it more generally, if the URL can be determined on the client, then use PUT. If it is determined on the server, then use POST. For example, many resources use the database's auto-incremented primary key as identification information, and create The identification information of the resource can only be provided by the server. At this time, it must be used

POSTPOST /users HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
    
    
  "name": "John Doe",
  "age": 30,
  "email": "[email protected]"
}

In the above example, the client uses the POST method to create a new user and sends the user information to the server in JSON format.
PUT: Update resources. When a client sends a request to the server using the PUT method, the server updates the representation of the resource associated with the request URI. Used to modify the content of data, but resources will not increase

PUT /users/1 HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
    
    
  "name": "John Doe",
  "age": 31,
  "email": "[email protected]"
}

In the above example, the client uses the PUT method to update the user information with ID 1, and sends the updated user information to the server in JSON format.
DELETE: Delete resources. When a client sends a request to the server using the DELETE method, the server deletes the resource associated with the request URI.

DELETE /users/1 HTTP/1.1
Host: api.example.com

In the above example, the client uses the DELETE method to delete the user information with ID 1.
PATCH: used to update some resources. When a client sends a request to the server using the PATCH method, the server updates some of the properties of the resource associated with the request URI.

PATCH /users/1 HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
    
    
  "age": 31
}

In the above example, the client uses the PATCH method to update the age information of the user with ID 1, and sends the updated user information to the server in JSON format.

HEAD: Used to get the metadata of a resource but does not return the actual response body. When a client sends a request to the server using the HEAD method, the server returns metadata about the resource associated with the request URI, such as the resource's size and modification time.

HEAD /users HTTP/1.1
Host: api.example.com

In the above example, the client uses the HEAD method to obtain metadata for all users and does not return the actual response body.
OPTIONS: Used to obtain metadata for HTTP methods and resources supported by the server. When a client sends a request to the server using the OPTIONS method, the server returns the supported HTTP methods and metadata for the resource associated with the request URI.

OPTIONS /users HTTP/1.1
Host: api.example.com

In the above example, the client uses the OPTIONS method to obtain all the HTTP methods and metadata supported by the user.

We use the annotations provided by SpringBoot to define various operations of RESTful Web services, such as @RestController, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PathVariable annotations. These annotations can help us define various operations of RESTful Web services more conveniently.

The difference between GET and POST:

  1. The data of the GET request will be appended to the URL (that is, the data is placed in the HTTP protocol header) to split the URL and transfer data. The parameters are connected with &, such as: getCitycode?lat=100.22&lon=35.33; POST submits The data is placed in the body of the HTTP packet.
  2. On the browser, the data submitted by GET method is limited. For example, sometimes the requested URL is too long and an error will be returned; but if it is a client GET request, there is no data limit. There is no limit to POST and a larger amount of data can be transferred.
  3. POST is more secure than GET. The security mentioned here is not the same concept as the "security" mentioned by GET above. The meaning of "security" above is just not to modify the data, and the meaning of security here is the true meaning of Security. For example: submit data through GET, the username and password will appear in clear text on the URL, and check the history of the browser. View the parameters of the GET request, such as login account password, search keywords, personal information, etc.

The difference between POST and PUT in creating resources is whether the name (URI) of the created resource is determined by the client. For example, if I add a java category to my blog post, and the generated path is the category name/categories/java, then the PUT method can be used.
Both the PUT and POST method semantics mean to modify the resource status, so they are not safe. However, the PUT method is idempotent, while the POST method is not. The reason for this design is: The
HTTP protocol stipulates that when the POST method modifies the resource status, the URL indicates the parent resource of the resource, and the ID information of the resource to be modified is in carried in the request body. When the PUT method modifies the resource status, the URL directly indicates the resource to be modified. Therefore, when creating resources, repeated submission of a POST request may produce two different resources, while repeated submission of a PUT request will only affect the resource specified in its URL, that is, only one resource will be created.

7. Describe the common ways that Java reads and writes Excel (answers can be answered with text explanations or code examples).

The main reason why EasyExcel can greatly reduce the memory usage is that when parsing Excel, the file data is not loaded into the memory all at once. Instead, the data is read line by line from the disk and parsed one by one.
EasyExcel adopts a row-by-row parsing mode and notifies processing of the parsing results of a row in the observer mode.

1. Java reads the contents of the Excel table:

  • Prepare entity class, converter conversion class
  • Prepare to import the listener, which is mainly used to monitor and read Excel file data. It is used to read data line by line. It needs to inherit the EasyExcel method AnalysisEventListener. There are three overriding methods (read data operation, read header operation, read data Operation after completion)
  • Use the EasyExcel.read method to specify the file path to read, which entity class to use to read, the listener object to use, which sheet to read, and so on.
public class ExceListener extends AnalysisEventListener<UserData> {
    
    
    /**
     * 进行读的操作具体执行方法,一行一行的读取数据
     * 从第二行开始读取,不读取表头
     *
     * @param userData
     * @param analysisContext
     */
    @Override
    public void invoke(UserData userData, AnalysisContext analysisContext) {
    
    
        System.out.println(userData);
    }

    /**
     * 读取表头信息
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
    
    
        super.invokeHeadMap(headMap, context);
        System.out.println("表头信息:" + headMap);
    }

    /**
     * 读取完数据的操作
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    
    
    }
}
private static void read() {
    
    
    // 指定读的路径
    String fileName = "D:\1627870562085.xlsx";
    //  调用读的方法
    EasyExcel.read(fileName, UserData.class, new ExceListener())
        .sheet().doRead();
}

2. Generate data into an Excel table through java:

  • Import the corresponding package and create the entity class
  • When exporting data, you need to call the write method of EasyExcel to write to a file or write to an output stream. Specify which entity class to use to write the file, sheet specifies the Excel file page sheet value, dowrite (written data collection)
private void writer() {
    
    
        List<UserData> userData = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
    
    
            UserData data = new UserData();
            data.setUid(i);
            data.setName("zdk" + i);
            userData.add(data);
        }
        // 指定写的路径
        String fileName = "D:\\" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,
        // 名字为模板 然后文件流会自动关闭
        EasyExcel.write(fileName, UserData.class)
                .sheet("模板")
                .doWrite(userData);
 }

8. Coding to create multi-threads. (4 ways to create multithreading)

Inherit the Thread class, implement the Runnable interface, implement the Callable interface, and thread pool;

The first one: inherit the Thread class:

  1. Create a subclass that inherits from Thread class
  2. Rewrite run() of the Thread class and declare the operations performed by this thread in run()
  3. Create an object of a subclass of Thread class
  4. Call start() through this object
/**
 * 多线程的创建,方式一:继承于Threadlei
 * 1.创建一个继承于Thread类的子类
 * 2.重写Thread类的run()  将此线程执行的的操作声明在run()中
 * 3.创建Thread类的子类的对象
 * 4.通过此对象调用start()
 *
 * 例子:遍历100以内所有的偶数
 */
public class ThreadTest {
    
    
    public static void main(String[] args) {
    
    
        //3.创建Thread类的子类的对象
        MyThread myThread = new MyThread();

        //4.通过此对象调用start()  ①启动当前线程 ②调用当前线程的run()
        myThread.start();

        //不能通过myThread.run()的方式启动线程

        //再启动一个线程
        MyThread myThread1 = new MyThread();
        myThread1.start();

        //如下操作仍然是在main()线程中执行的
        for (int i = 0;i < 100 ;i++){
    
    
            if (i % 2 != 0){
    
    
                System.out.println(Thread.currentThread().getName() + ":"+"hello");
            }
        }
    }
}

//  1.创建一个继承于Thread类的子类
class MyThread extends Thread {
    
    
    //2.重写Thread类的run()
    @Override
    public void run() {
    
    
        for (int i = 0;i < 100 ;i++){
    
    
            if (i % 2 == 0){
    
    
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

Second type: Implement the Runnable interface

  1. Create a class that implements the Runnable interface
  2. Implement the class to implement the abstract method in Runnable: run()
  3. Create an object that implements a class
  4. Pass this object as a parameter to the constructor of the Thread class to create an object of the Thread class
  5. Call start() through an object of class Thread
/**
 * 创建多线程的方式二:实现Runnable接口
 * 1.创建一个实现了Runnable接口的类
 * 2.实现类去实现Runnable中的抽象方法:run()
 * 3.创建实现类的对象
 * 4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
 * 5.通过Thread类的对象调用start()
 *
 * 比较创建线程的两种方式:
 * 开发中优先选择实现Runnable接口的方式
 * 原因:1.实现的方式没有类的单继承性的局限性
 *      2.实现的方式更适合来处理多个线程有共享数据的情况
 *
 * 联系:都实现了Runnable接口
 * 相同点:两种方式都需要重写run()方法,将线程要执行的逻辑声明在run()中
 *
 */
public class ThreadTest1 {
    
    
    public static void main(String[] args) {
    
    
        // * 3.创建实现类的对象
        MyThread myThread = new MyThread();
        // * 4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
        Thread thread1 = new Thread(myThread);
        // * 5.通过Thread类的对象调用start() ①启动线程 ②调用当前线程的run()
        thread1.start();

        Thread thread2 = new Thread(myThread);
        thread2.start();
    }
}

// * 1.创建一个实现了Runnable接口的类
class MyThread implements Runnable{
    
    
    // * 2.实现类去实现Runnable中的抽象方法:run()
    @Override
    public void run() {
    
    
        for (int i = 0; i < 100; i++) {
    
    
            if (i % 2 == 0) {
    
    
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

The third type: implement the Callable interface

  1. Create an implementation class that implements Callable
  2. Implement the call method and declare the operations that this thread needs to perform in call()
  3. Create an object of the Callable interface implementation class
  4. Pass the object of the Callable interface implementation class as a parameter to the FutureTask constructor to create an object of FutureTask
  5. Pass the FutureTask object as a parameter to the constructor of the Thread class, create the Thread object, and call the start() method
  6. Get the return value in the call method in Callable
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 创建线程的方式三:实现Callable接口。   JDK5.0新增
 *
 * 如何理解实现Callable接口的方式创建多线程的方式比是实现Runnable接口创建多线程方式强大
 * 1.call()可以有返回值
 * 2.call()可以抛出异常
 */
public class ThreadNew {
    
    
    public static void main(String[] args) {
    
    
        //3.创建Callable接口实现类的对象
        NumThread numThread = new NumThread();
        //4.将Callable接口实现类的对象作为参数传递到FutureTask构造器中,创建FutureTask的对象
        FutureTask futureTask = new FutureTask(numThread);


        //5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()方法
        Thread thread1 = new Thread(futureTask);
        thread1.start();

        try {
    
    
            //6.获取Callable中call方法中的返回值
            //get()返回值即为FutureTask构造器参数Callable实现重写的call()返回值。
            Object sum = futureTask.get();
            System.out.println(" 总和为:" + sum);

        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        } catch (ExecutionException e) {
    
    
            e.printStackTrace();
        }
    }
}

//1.创建一个实现Callable的实现类
class NumThread implements Callable{
    
    
    //2.实现call方法,将此线程需要执行的操作声明在call()中
    @Override
    public Object call() throws Exception {
    
    
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
    
    
            if(i % 2 == 0){
    
    
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}

The fourth method: Thread pool method

  1. Provides a thread pool with a specified number of threads
  2. To perform operations on a specified thread, you need to provide an object that implements the Runnable interface or the Callable interface implementation class.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 创建线程的方式四:使用线程池
 *
 * 好处:1.提高响应速度(减少创建新线程的时间)
 *      2.降低资源消耗(重复利用线程池中的线程,不需要每次都创建)
 *      3.便于线程管理
 *
 *      corePoolSize:核心池的大小
 *      maximumPoolSize:最大线程数
 *      keepAliveTime:线程没有任务时最多保持多长时间后会终止
 */
public class ThreadPool {
    
    
    public static void main(String[] args) {
    
    
        //1.提供指定线程数量的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        ThreadPoolExecutor service1 = (ThreadPoolExecutor) executorService;
        //设置线程池的属性
        service1.setCorePoolSize(10);

        //2.执行指定线程的操作,需要提供实现Runnable接口或Callable接口实现类的对象
        executorService.execute(new NumberThread());//适合使用于Runnable
        //executorService.submit();//适合使用与Callable

        executorService.execute(new NumberThread1());

        //关闭线程池
        executorService.shutdown();
    }
}

class NumberThread implements Runnable{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i <= 100 ; i++) {
    
    
            if(i % 2 == 0){
    
    
                System.out.println(Thread.currentThread().getName() + ":" +i);
            }

        }
    }
}

class NumberThread1 implements Runnable{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i <= 100 ; i++) {
    
    
            if(i % 2 != 0){
    
    
                System.out.println(Thread.currentThread().getName() + ":" +i);
            }

        }
    }
}

Insert image description here

9. The values ​​stored in list are ordered and repeatable, while the values ​​stored in set are disordered and cannot be repeated. So on what basis does set determine that it is not repeatable?

  1. TreeSet, the bottom layer is a TreeMap, and the subclass uses the Comparable interface to realize the judgment of duplicate elements, but the overall characteristic of the Set collection is that it does not allow duplicate elements to be saved.
  2. HashSet, the bottom layer is a HashMap, and the value is the key of the HashMap. Determining the repetition of elements is implemented by using the method in the Object class:
    • Object encoding: public int hashCode();
    • Object comparison: public boolean equals(Object obj);

When judging duplicate elements, first use hashCode() to perform code matching. If the code does not exist, it means that the data does not exist, proving that there is no duplication. If the code exists, use the equals() method to further compare the objects. If duplicates are found, the data cannot be saved.

In the Java program, the real judgment and processing of repeated elements is completed by the two methods of hashCode() and equals().
Only in the case of sorting requirements (TreeSet) will be implemented using the Comparable interface.

3. Database knowledge

1. Human resources table: Basic user information data stored in HrmResource. Use three different databases: SqlServer, Oracle, and MySQL to query the data from items 11 to 20 (Note: The table contains unique primary key IDs, but they are not consecutive)

-- 1.mysql : select * from tableName where 条件 limit 当前页码*页面容量-1 , 页面容量
select * from HrmResource limit 11,10; -- MySQL   limit(起始行,每行多少页)


--2.oracle 查询20-40条记录   注:第一种方法比第二种方法效率高
第一种方法:select * from (select A.* ,rownum rn from (select * from table_name) A where rn<=40) where rn>=20;

第一种方法:select * from (select A.* ,rownum rn from (select * from table_name) A ) where rn between 20 and 40;


-- 3. sql server分页查询:  select top n <字段1>,...,<字段n> from <表名>
假设现在有这样的一张表:
 CREATE TABLE test
 (
  id int primary key not null identity,
  names varchar(20)
 )
 然后向里面插入大约1000条数据,进行分页测试
 假设页数是10,现在要拿出第5页的内容
 
 方法一:原理:拿出数据库的第5页,就是40-50条记录。首先拿出数据库中的前40条记录的id值,然后再拿出剩余部分的前10条元素
 select top 10 * from test where id not in
 (
  --40是这么计算出来的:10*(5-1)
  select top 40 id from test order by id
 )
 order by id

方法二:原理:先查询前40条记录,然后获得其最id值,如果id值为null的,那么就返回0
 然后查询id值大于前40条记录的最大id值的记录。这个查询有一个条件,就是id必须是int类型的。
select top 10 * from test where id >
 (
  select isnull(max(id),0) from 
   ( select top 40 id from test order by id ) A
 )
 order by id
 
 方法三:原理:先把表中的所有数据都按照一个rowNumber进行排序,然后查询rownuber大于40的前十条记录 
 这种方法和oracle中的一种分页方式类似,不过只支持2005版本以上的
 row_number()函数,为结果集的分区中的每一行分配一个连续的整数。
 OVER()是一个开窗函数,对集合进行聚合计算
 select top 10 * from 
 (
  select row_number() over(order by id) as rownumber,* from test
 ) A
 where rownumber > 40
 
 方法四:存储过程
1. 创建存储过程
alter procedure pageDemo
@pageSize int,
@page int
AS
declare @temp int
set @temp=@pageSize*(@page - 1)
begin
 select top (select @pageSize) * from test where id not in (select top (select @temp) id from test) order by id
end

2. 执行存储过程
exec 10,5

2. The data structure of the attendance and sign-in table is as follows: Table name: hrmschedulesign. Please use SQL to query: the sign-in and check-out times of all users yesterday;

ID userid signdate signtime clientaddress
1 A01 2019-06-17 08:32:40 192.168.3.232
2 A01 2019-06-17 10:30:22 192.168.3.232
3 A01 2019-06-17 18:15:30 192.168.3.232
4 A02

(Note: Each user will have 1-N check-in records in the attendance sheet. The earliest time of each day is the check-in data, and the latest time is the check-out data. Issues spanning multiple days do not need to be considered)

select userid,min(signtime) startTime,max(signtime) endTime from hrmschedulesign 
where (sysdate - to_date(signdate,'YYYY-MM-DD'))=1 group by userid;

通过where (sysdate - to_date(signdate,'YYYY-MM-DD'))=1 筛选出昨天的所有数据,
select sysdate from dual,可以得到目前系统的时间;
由于signdate不是标准的YYYY/MM/DD的形式,所以肯定不是date类型的,
因为我们在和sysdate比较的时候需要通过to_date()函数把字符串变成date类型的数据,
之后就可以比较了,得出的就是天数,对于signtime来说,可以使用min()max()进行比较,
最后在通过userid进行分组

3. Briefly describe the common database index types and functions.

1. Ordinary index (NORMAL)
does not have any restrictions.
2. Unique index (UNIQUE)
requires that the keyword value cannot be repeated and adds unique constraints.
3. Primary key index:
It is required that the keyword cannot be repeated or NULL. Also add primary key constraints.
4. The source of full-text index (FULLTEXT)
keywords is not the data of all fields, but the special keywords extracted from the fields. MySQL support is not very good. Generally, a third-party search engine is used to solve the elasticsearch tool to complete the search; FULLTEXT works best when used to search a long article. Used for relatively short text, if it is only one or two lines, ordinary INDEX can also be used

Index advantages:

  • Fast query, greatly speeding up data retrieval;
  • Create a unique index to ensure the uniqueness of each row of data in the database table;
  • Connections between accelerator tables and tables;
  • When using grouping and sorting clauses for data retrieval, the time it takes to group and sort within a query can be significantly retrieved.

Index disadvantages:

  • Indexes need to occupy physical space. When the frequency of additions, deletions and modifications is greater than the frequency of queries, it is not recommended to use indexes; adding indexes to unnecessary fields will result in poor performance.
  • When adding, deleting, and modifying data in the table, the index must be dynamically maintained, which reduces the data maintenance speed.

1) The difference between B+ index and Hash index:
The data structure of B+ index is a red-black tree, and the query time complexity is Ologn level. The storage data structure of the Hash index is a hash table, and the query time complexity is O(1) level. Yes,
the reason why we use B+ index is because Hash is unordered and does not support range search and sorting functions.
2) The difference between primary key index and ordinary index:
Usually when we use the index, we use the primary key query: because the data of the primary key index is stored That row of data (innodb engine), and the data of the ordinary index (auxiliary index) stores the primary key, and needs to be queried again through the primary key.

4. Write the SQL to create a common index for the title field of the workplan table.

创建索引
create index index_name on table_name(column_name)

EX:
create index index_id on workplan(title asc)

修改表结构(添加索引)
alter table table_name add index index_name(column_name)

EX:
alter table workplan add index index_id(title asc)

创建表时,直接指定索引
create table table_name(
  id int not null,
  username varchar(64) not null,
  index [index_name] (username)  
);

删除索引
drop index [index_name] on table_name

Guess you like

Origin blog.csdn.net/m0_46459413/article/details/131955794