Java basics (slowly updated)

1.1. What is the difference between Array and List?

Both Array and List are sequential tables.

  • Array is a continuous storage structure, while List is a discontinuous storage structure. Each node of the List has a Next attribute, which records the address of its next node.
  • The array must be allocated a fixed size when it is initialized . Since the space of List does not need to be continuous, there is no need to specify the initial size.

Array is best used when a lot of lookup operations are required. When frequent insertion and deletion operations are required, it is best to use List instead of Array.

1.2. What is the difference between == and equals, equals and hashcode?

"== Interpretation"

The effect of == is different for basic types and reference types, as follows:

  • Basic type: the comparison is whether the values ​​are the same;
  • Reference type: the comparison is whether the references are the same;

"Interpretation of equals"

equals is essentially ==, but String and Integer rewrite the equals method and turn it into a value comparison. .

Summary : == is a value comparison for basic types, and a reference comparison for reference types; and equals is a reference comparison by default, but many classes rewrite the equals method, such as String, Integer, etc. to change it to It becomes a value comparison, so in general, equals compares whether the values ​​are equal.

///

"hashcode interpretation"

The role of hashCode() is to get the hash code, also known as the hash code. Actually returns an int integer.

  • If two objects are equal (equals), their hashcode must be the same;
  • Conversely, if two objects have the same hashcode, they are not necessarily equal (equals).

Expansion: In the map, the data is generally stored in the form of an array + linked list , and the position (subscript) where the value is stored in the array is determined by calculating the hashcode of the key. If there is a hash conflict, use a linked list to store the conflicting elements at the corresponding subscript position . That is, two elements having the same hashcode value can only indicate that the two elements have the same array subscript, but there is no guarantee whether they are the same object, because there may be hash conflicts, and the position of the element in the linked list is uncertain. And equals means that the position of the elements in the linked list is also the same.

1.3. What is the role of final in Java?

  • The final modified class is called the final class, which cannot be inherited.
  • Final modified methods cannot be overridden.
  • Variables modified by final are called constants. Constants must be initialized, and the value cannot be modified after initialization.

1.4. What are the 4 ways of rounding floating-point types in Java?

  • Math.ceil(), ceil means the ceiling, which means rounding up. For example, 1.9 returns 2, -1.9 returns -1, and the 大于等于original number is always returned
  • Math.floor(), floor means the floor, which means rounding down. For example, 1.9 returns 1, -1.9 returns -2, and the 小于等于original number is always returned
  • Math.rint(), which means rounding close to an integer, as the name implies, whichever one is closer to the integer. For example, 1.6 is close to 2, so take 2; 1.4 is close to 1, so take 1; what about 1.5, 1.5 is very close to 1 and 2, so take an even number at this time.
  • Math.round(), performing mathematical rounding (+0.5 rounded down).
Math.ceil(1.1); // 2

Math.floor(1.6); // 1

Math.rint(1.5); // 2
Math.rint(2.5); // 2

Math.round(1.5); // 2
Math.round(-1.6); // 等价于 Math.floor(-1.6 + 0.5) = -2

1.5. What are the basic data types in Java? Is String a primitive data type?

There are 8 basic data types in Java, namely:

  • 6 numeric types:
    • 4 integer types: byte, short, int,long
    • 2 floating point types: float,double
  • 1 character type:char
  • 1 Boolean type: boolean.

String is not a primitive type, String is an object.

1.6. What classes are there for manipulating strings in Java? What's the difference between them?

The classes for manipulating strings are: String, StringBuffer, StringBuilder.

String declares an immutable object, each operation will generate a new String object, and then point the pointer to the new String object
StringBuffer, StringBuilder can operate on the basis of the original object, so in the case of frequently changing the string content Best not to use String.

The biggest difference between StringBuffer and StringBuilder is: StringBuffer is thread-safe, while StringBuilder is non-thread-safe, but the performance of StringBuilder is higher than StringBuffer, so it is recommended to use StringBuilder in a single-threaded environment, and recommended to use StringBuffer in a multi-threaded environment.

1.7. Is String str="i" the same as String str=new String("i")?

Not the same, because the way memory is allocated is different. String str="i", the Java virtual machine will allocate it to the constant pool; while String str=new String("i") will be allocated to the heap memory.

1.8. How to reverse a string?

Use the reverse() method of StringBuilder or stringBuffer.

// StringBuffer reverse
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("abcdefg");
System.out.println(stringBuffer.reverse()); // gfedcba

// StringBuilder reverse
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("abcdefg");
System.out.println(stringBuilder.reverse()); // gfedcba

1.9. What are the commonly used methods of the String class?

  • indexOf(): Returns the index of the specified character.
  • charAt(): Returns the character at the specified index.
  • replace(): String replacement.
  • trim(): Remove blanks at both ends of the string.
  • split(): Split the string and return a split string array.
  • getBytes(): Returns a byte type array of strings.
  • length(): Returns the string length.
  • toLowerCase(): Convert the string to lowercase letters.
  • toUpperCase(): Convert the string to uppercase characters.
  • substring(): Intercept the string.
  • equals(): String comparison.

1.10. Do abstract classes have to have abstract methods?

unnecessary.
Abstract classes do not necessarily have abstract methods, for example:

abstract class Cat{
    
    
    public static void sayHi(){
    
    
        System.out.println("hi~");
    }
}

1.11. What is the difference between ordinary classes and abstract classes?

  • Ordinary classes cannot contain abstract methods, abstract classes can contain abstract methods.
  • Abstract classes cannot be instantiated directly, ordinary classes can be instantiated directly.
// 抽象类可以通过子类继承,实例化子类的时候抽象类也会被实例化
abstract class B {
    
    
    private String str;

    public B(String tips) {
    
    
        this.str = tips;
        System.out.println("父类已经实例化:" + str);
    }

    public abstract void play();
}

public class A extends B {
    
    

    public A(String tips) {
    
    
        super(tips);
        System.out.println("子类已经实例化");
    }

    @Override
    public void play() {
    
    
        System.out.println("我实现了父类的方法");
    }

    public static void main(String[] args) {
    
    
        B aa = new A("6666");
    }
}

// 父类已经实例化:6666
// 子类已经实例化

1.12. Can an abstract class be decorated with final?

cannot.
Defining an abstract class is to allow other classes to inherit. If it is defined as final, the class cannot be inherited, which will cause conflicts with each other, so final cannot modify abstract classes.

1.13. What is the difference between an interface and an abstract class?

Implementation : Subclasses of abstract classes use extends to inherit; interfaces must use implements to implement interfaces.
Constructor : Abstract classes can have constructors, but interfaces cannot.
Number of implementations : A class can implement many interfaces, but can only inherit one abstract class.
Access modifiers : Methods in interfaces are modified by public by default, and methods in abstract classes can be any access modifiers.

1.14. What are overriding and overloading?

  • Override : The subclass rewrites the implementation process of the access-allowed method of the parent class, and the return value and formal parameters cannot be changed.
  • Overloading (overlord) : In a class, multiple methods have the same method name, but different parameters. The return types can be the same or different.
public class TestCs {
    
    
    public int test(){
    
    
        System.out.println("test1");
        return 1;
    }
    public void test(int a){
    
    
        System.out.println("test2");
    }
    //以下两个参数类型顺序不同
    public String test(int a,String s){
    
    
        System.out.println("test3");
        return "returntest3";
    }
    public String test(String s,int a){
    
    
        System.out.println("test4");
        return "returntest4";
    }
    public static void main(String[] args){
    
    
        TestCs o = new TestCs(); // test1
        System.out.println(o.test()); // 1
        o.test(1); // test2
        System.out.println(o.test(1,"test3")); // test3 // returntest3
        System.out.println(o.test("test4",1)); // test4 // returntest4
    }
}

1.15. Explain the three major features of Java: encapsulation, inheritance, polymorphism?

Encapsulation : hide some information of the class inside the class, and do not allow external programs to make direct access calls. The operation and access to hidden information is realized through the methods provided by this class.

// 使用private修饰符,表示最小的访问权限。
// 对成员变量的访问,统一提供setter,getter方法。
public class Student {
    
     
    // 属性
    private String name;
 
    // 无参构造函数
    public Student() {
    
    
    }
 
    // 有参构造函数
    public Student(String name) {
    
    
        this.name = name;
    } 
    
    // getter setter 方法
    public String getName() {
    
    
        return name;
    } 
    
    public void setName(String name) {
    
    
        this.name = name;
    } 
    
    // toString 方法
    @Override
    public String toString() {
    
    
        return "TestStudent{" +
                "name='" + name + '\'' +
                '}';
    }
}

Inheritance : You can make the subclass have the properties and methods of the parent class, and you can also redefine and add properties and methods in the subclass.class B extends A

Polymorphism : The premise of polymorphism: inheritance + rewriting. Polymorphism is the ability to have multiple different manifestations or morphologies of the same behavior.

class Animal{
    
    
    public Animal() {
    
     // 子类会默认使用父类的无参构造
        System.out.println("我是父类的无参构造");
    }

    public void eat(){
    
     // 定义父类的方法
        System.out.println("动物会吃东西");

    }

}
// 创建Animal的子类Cat 
class Cat extends Animal{
    
        
    //子类可以重写父类的方法
    public void eat(){
    
    
        System.out.println("小猫喜欢吃小鱼干!");
    }
    // 定义子类的私有方法
    private void jump(){
    
    
        System.out.println("小猫会跳");
    }
}

// Animal cat = new Cat();

1.16. What is the singleton pattern? How to achieve it?

The singleton pattern has the following characteristics:

  1. A singleton class can have only one instance.
  2. A singleton class must create its own unique instance.
  3. A singleton class must provide this instance to all other objects.

The singleton pattern ensures that a class has only one instance, and instantiates itself and provides this instance to the entire system.

//懒汉式单例类.在第一次调用的时候实例化自己 
public class Singleton {
    
    
    private Singleton() {
    
    }
    private static Singleton single=null;
    //静态工厂方法 
    public static Singleton getInstance() {
    
    
         if (single == null) {
    
      
             single = new Singleton();
         }  
        return single;
    }
}

container

2.1. What are the containers in Java?

Java containers are divided into Collectiontwo Mapcategories and there are many subcategories under them, as follows:

  • Collection
    • List (ordered collection)
      • ArrayList
      • LinkedList
      • Vector
        • Stack
    • Set (unrepeated collection)
      • HashSet
        • LinkedHashSet
      • TreeSet
  • Map
    • HashMap
      • LinkedHashMap
    • TreeMap
    • ConcurrentHashMap
    • Hashtableinsert image description here

2.2. What is the difference between Collection and Collections?

  • Collection is a collection interface, which provides general interface methods for basic operations on collection objects, and all collections are its subclasses, such as List, Set, etc.
  • Collections is a wrapper class that contains many static methods and cannot be instantiated, just like a tool class, such as the sorting method provided: Collections.sort(list).

2.3. What is the difference between List, Set, and Map?

The difference between List, Set, and Map is mainly reflected in two aspects: 元素是否有序, 是否允许元素重复.
The difference between the three is as follows:
insert image description here

2.4. What is the difference between HashMap and Hashtable?

  • Storage : HashMap allows key and value to be null, but Hashtable does not.
  • Thread safety : Hashtable is thread safe, while HashMap is not thread safe.

Recommended use: As you can see in the class annotation of Hashtable, Hashtableit is a reserved class that is not recommended to use. It is recommended to use instead in a single-threaded environment HashMap. If multi-threaded use is required, use ConcurrentHashMapinstead.

2.5. How to decide to use HashMap or TreeMap?

  • For operations such as inserting, deleting, and locating an element in the Map, HashMap is the best choice, because relatively speaking, the insertion of HashMap will be faster;
  • But if you want to perform ordered traversal on a key collection, then TreeMap is a better choice.

2.6. Tell me about the implementation principle of HashMap?

HashMap is implemented based on the Hash algorithm. We store it through put (key, value) and get it through get (key).
When the key is passed in, HashMap will key.hashCode()calculate the hash value according to and save the value in according to the hash value bucket.
When the calculated hash values ​​are the same, we call it a hash conflict. HashMap uses a linked list and a red-black tree to store values ​​with the same hash value. When the number of hash conflicts is relatively small, use 链表otherwise 红黑树.

bucket : The so-called bucket is for HashMap and its subclasses, they use the Hash algorithm to determine the storage location of the elements in the collection. When the system starts to initialize the HashMap, the system will create an Entry array with a length of capacity. The location where elements can be stored in this array is called a "bucket". Each bucket has its specified index, and the system can use its index to Quickly access the
elements stored in the bucket.

2.7. Tell me about the implementation principle of HashSet?

HashSet is implemented based on HashMap. The bottom layer of HashSet uses HashMap to save all elements, so the implementation of HashSet is relatively simple. The operations related to HashSet are basically completed by directly calling the relevant methods of the underlying HashMap HashSet不允许重复的值.

2.8. What is the difference between ArrayList and LinkedList?

  • Data structure implementation: ArrayList is 动态数组a data structure implementation, and LinkedList is 双向链表a data structure implementation.
  • Random access efficiency: ArrayList is more efficient than LinkedList in random access, because LinkedList is a linear data storage method, so you need to move the pointer to search from front to back.
  • Addition and deletion efficiency: LinkedList is more efficient than ArrayList in non-head and tail addition and deletion operations, because ArrayList addition and deletion operations will affect the subscripts of other data in the array.

In general, ArrayList is recommended when elements in the collection need to be read frequently, and LinkedList is recommended when there are many insertion and deletion operations.

2.9. How to realize the conversion between array and List?

  • Array to List: Use Arrays.asList(array)to convert.
  • Convert List to array: Use the method that comes with List toArray().

Sample code:

// 数组转list
String[] array = new String[]{
    
    "薄荷分享","bhshare.cn"};
Arrays.asList(array);

// list转数组
List<String> list = new ArrayList<String>();
list.add("薄荷分享");
list.add("bhshare.cn");
list.toArray();

2.10. What is the difference between ArrayList and Vector?

  • Thread safety: Vector uses Synchronized to achieve thread synchronization, which is thread safe, while ArrayList is not thread safe.
  • Performance: ArrayList is better than Vector in terms of performance.
  • Expansion: Both ArrayList and Vector will dynamically adjust the capacity according to actual needs, but the expansion of Vector will double each time, while ArrayList will only increase by 50%.

2.11. What is the difference between Array and ArrayList?

  • Array can store basic data types and objects, while ArrayList can only store objects.
  • Array is specified with a fixed size, while the size of ArrayList is automatically expanded.
  • There are not as many built-in methods in Array as in ArrayList, such as addAll, removeAll, iteration and other methods only in ArrayList.

2.12. What is the difference between poll() and remove() in Queue?

  • The same point: both return the first element and delete the returned object in the queue.
  • The difference: if there is no element, poll() will return null, and remove() will directly throw NoSuchElementException.

Code example:

Queue<String> queue = new LinkedList<String>();
queue.offer("string"); // add
System.out.println(queue.poll());
System.out.println(queue.remove());
System.out.println(queue.size());

2.13. Which collection classes are thread-safe?

  • Thread safety: Vector, HashTable, Stack, enumeration, java.util.concurrentall collection classes under the package, such as: ConcurrentHashMap,CopyOnWriteSet
  • Non-thread safe: HashMap, ArrayList

2.14. What is Iterator?

The Iterator interface provides an interface for traversing any Collection. We can get iterator instances from a Collection using the iterator method.
Iterators replace Enumeration in the Java collection framework, and iterators allow the caller to remove elements during iteration.

2.15. How to use Iterator? What are the characteristics?

Iterator usage code is as follows:

List<String> list = new ArrayList<>();
... // add list
Iterator<String> it = list.iterator();
while(it.hasNext()){
    
    
  String obj = it.next();
  System.out.println(obj);
}

The feature of Iterator is safer, because it can ensure that when the currently traversed collection elements are changed, ConcurrentModificationExceptionan exception will be thrown.

2.16. What is the difference between Iterator and ListIterator?

  • Iterator can traverse Set and List collections, while ListIterator can only traverse List.
  • Iterator can only traverse in one direction, while ListIterator can traverse in both directions (forward/backward traversal).
  • ListIterator inherits from the Iterator interface, and then adds some additional functions, such as adding an element, replacing an element, and getting the index position of the previous or following element.

2.17. How to ensure that a collection cannot be modified?

You can use Collections.unmodifiableCollection(Collection c)the method to create a read-only collection so that any operations that mutate the collection will throw Java.lang.UnsupportedOperationExceptionan exception.

Sample code:

List<String> list = new ArrayList<>();
list.add("x");
Collection<String> clist = Collections.unmodifiableCollection(list);
clist.add("y"); // 运行时此行报错
System.out.println(list.size());

Multithreading

3.1. What is the difference between parallelism and concurrency?

  • Concurrency: Handing tasks to processors at different points in time for processing. At the same point in time, tasks do not run concurrently.
  • Parallelism: Assign each task to each processor to complete independently. At the same point in time, the tasks must be running concurrently.

Illustration:
insert image description here


data structure

4.1. What are the common sorting algorithms?

insert image description here

  • Bubble sort : Change the largest to the last, and then change the second largest to the penultimate...

     public static void bubbleSort(int[] args) {
          
          
          int len = args.length;
          while (len > 0) {
          
          
              for (int i = 0; i < len - 1; i++) {
          
          
                  int next = i + 1;
                  if (args[i] > args[next]) {
          
          
                      int temp = args[next];
                      args[next] = args[i];
                      args[i] = temp;
                  }
              }
              len--;
          }
      }
    
  • Quick sort : Take a value from the sequence, place the value larger than this value on its right, place the value smaller than this value on its left, and repeat (recursively) this process in the left and right areas until each area There is only one number.

    public void quickSort(int[] target, int left, int right) {
          
          
          if (left >= right) {
          
          
              return;
          }
          int pivot = target[left];// 基准点
          int lo = left;
          int hi = right;
          while (lo < hi) {
          
          
    
              while (target[hi] >= pivot && lo < hi) {
          
          
                  hi--;
              }
              //把右边受阴元素和左边换
              target[lo] = target[hi];
    
              while (target[lo] <= pivot && lo < hi) {
          
          
                  lo++;
              }
              //把左边受阴元素和右边换
              target[hi] = target[lo];
          }
          //把拿出来的元素放回去
          target[lo] = pivot;
          
          quickSort(target, left, lo - 1);
          quickSort(target, lo + 1, right);
      }
    

4.2. Level order traversal of binary tree?

  • Idea : Use the idea of ​​breadth-first search (BFS) to traverse layer by layer.

  • Achieve :

      1. 创建一个队列,初始时将根节点入队。
    
      2. 如果队列不为空,执行以下操作:
    
      	2.1 弹出队首元素,即当前层要遍历的结点。
    
      	2.2 如果当前结点有左儿子,则将其左儿子入队。
    
      	2.3 如果当前结点有右儿子,则将其右儿子入队。
    
      	2.4 将当前结点的值输出。
      	
      3. 重复步骤2,直到队列为空。
    
  • Java code :

    class TreeNode {
          
          
        int val;
        TreeNode left;
        TreeNode right;
    
        public TreeNode(int val) {
          
          
            this.val = val;
        }
    }
    // ----------
    public List<List<Integer>> levelOrder(TreeNode root) {
          
          
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
          
          
            return result;
        }
    
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
          
          
            int levelSize = queue.size(); // 当前层的节点数量
            List<Integer> level = new ArrayList<>(); // 当前层的节点值列表
            for (int i = 0; i < levelSize; i++) {
          
          
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
          
          
                    queue.add(node.left);
                }
                if (node.right != null) {
          
          
                    queue.add(node.right);
                }
            }
            result.add(level);
        }
    
        return result;
    }
    
    public static void main(String[] args) {
          
          
        TreeNode root = new TreeNode(0);
        root.left = new TreeNode(1);
        root.right = new TreeNode(10);
        root.left.left = new TreeNode(15);
        root.right.right = new TreeNode(5);
        System.out.println(levelOrder(root)); // [[0], [1, 10], [15, 5]]
    }
    
    

backend development

5.1. The difference between hibernate and mybatis?

  • MyBatis is a small, convenient, efficient, simple, direct, and semi-automated persistence layer framework, and Hibernate is a powerful, convenient, efficient, complex, indirect, and fully automated persistence layer framework.

Hibernate is recommended for systems with less demanding performance requirements, such as management systems and ERP, while MyBatis is recommended for systems with high performance requirements, fast response, and flexibility.

  • The biggest difference: For advanced queries , Mybatis needs to manually write SQL statements and ResultMap. Hibernate has a good mapping mechanism, developers do not need to care about SQL generation and result mapping , and can focus more on business processes.
    For simple logic, both Hibernate and MyBatis have corresponding code generation tools that can generate simple and basic DAO layer methods.
  • Development difficulty: The development difficulty of Hibernate is greater than that of Mybatis . The main reason is that Hibernate is complex and huge, and the learning cycle is long. Mybatis is relatively simple, and Mybatis mainly relies on the writing of sql, which makes developers feel more familiar.
  • SQL writing: The SQL of Mybatis is written manually, and the query fields can be specified as required . However, there is no log statistics of its own, so log4j is used to record logs. Hibernate can also write its own SQL to specify the fields that need to be queried, but this destroys the simplicity of Hibernate development . But Hibernate has its own log statistics.
  • Database scalability: Mybatis has poor scalability and migration because all SQL is written in a database . The specific relationship between Hibernate and the database is in XML, so HQL does not care much about the specific database used.
  • Caching mechanism: Because Hibernate has a good management mechanism for query objects, users do not need to care about SQL. Therefore, if there is dirty data when Hibernate uses the second-level cache, the system will report an error and prompt . In this regard, MyBatis needs to be very careful when using the second-level cache. If you cannot fully determine the scope of data update operations, avoid blind use of Cache. Otherwise, the emergence of Mybatis dirty data will bring great hidden dangers to the normal operation of the system .

5.2. Talk about the understanding of database indexing, the advantages and disadvantages of indexing?

  • Advantages of indexing : It can greatly improve the performance of the system.

    1. By creating a unique index, the uniqueness of each row of data in the database table can be guaranteed.
    2. It can greatly speed up the retrieval of data , which is the main reason for creating indexes.
    3. It can speed up the connection between tables, especially in realizing the referential integrity of data.
    4. When using grouping and sorting clauses for data retrieval, it can also significantly reduce the time for grouping and sorting in queries .
    5. By using the index, you can use the optimization hider during the query process to improve the performance of the system.
  • Disadvantages of indexing :

    1. Creating and maintaining indexes takes time , and this time increases with the amount of data.
    2. Indexes need to occupy physical space . In addition to data tables occupying data space, each index also occupies a certain amount of physical space. If you want to build a clustered index, the space required will be even larger.
    3. When adding, deleting, and modifying data in the table, the index must also be maintained dynamically, which reduces the speed of data maintenance .
  • The way to create an index :

    1. Create an index:create index <索引的名字> on table_name (列的列表);
    2. Modify table:alter table table_name add index [索引的名字] (列的列表);
    3. Specify the index when creating the table:create table table_name ( […], INDEX [索引的名字] (列的列表) );
  • To view the index :show index from table_name;

  • Index type :

    1. PRIMARY KEY (primary key index):mysql> alter table table_name add primary key ( ``column``)
    2. UNIQUE or UNIQUE KEY (unique index):mysql> alter table table_name add unique (``column``)
    3. FULLTEXT (full text index):mysql> alter table table_name add fulltext (``column``)
    4. INDEX (ordinary index):mysql> alter table table_name add index index_name ( ``column``)
    5. Multi-column index (clustered index):mysql> alter table ``table_name`` add index index_name ( ``column1``, ``column2``, ``column3`` )

5.3. What kind of fields are suitable/unsuitable for creating indexes?

  • Suitable for index creation :
    1. On the columns that often need to be searched, the search speed can be accelerated;
    2. On the column as the primary key, enforce the uniqueness of the column and the arrangement structure of the data in the organization table;
    3. On the columns that are often used in connection, these columns are mainly some foreign keys, which can speed up the connection;
    4. Create indexes on columns that often need to be searched based on ranges, because the indexes are sorted and the specified ranges are continuous;
    5. Create an index on the column that often needs to be sorted, because the index is already sorted, so that the query can use the sorting of the index to speed up the sorting query time;
    6. Create indexes on the columns that are often used in the WHERE clause to speed up the judgment of conditions.
  • Not suitable for indexing :
    1. Indexes should not be created for columns that are rarely used or referenced in queries. This is because, since these columns are rarely used, indexing or no indexing does not improve query speed. On the contrary, due to the increase of the index, the maintenance speed of the system is reduced and the space requirement is increased.
    2. Indexes should also not be added to columns with few data values. This is because, because these columns have very few values, such as the gender column of the personnel table, in the query results, the data rows of the result set account for a large proportion of the data rows in the table, that is, the data that needs to be searched in the table The ratio of rows is huge.
    3. For those columns defined as text, image and bit data types should not increase the index. This is because the amount of data in these columns is either quite large or takes very few values.
    4. Indexes should not be created when modification performance is far greater than retrieval performance. This is because modification performance and retrieval performance are contradictory to each other.

5.4. What is the data structure of the MySQL index and why the index fails?

  • Data structure : B+ tree
    • The default storage engine of MySQL is InnoDB, which uses B+ tree as the data structure of the index.
    • MySQL's MyISAM storage engine supports multiple index data structures, such as B+ tree index, R tree index, and Full-Text index. When the MyISAM storage engine creates a table, the primary key index created uses the B+ tree index by default.
  • Index invalidation:
    1. When we use left or left fuzzy matching, that is, like %xx or like %xx%, both methods will cause the index to fail;
    2. When we use functions on index columns in query conditions, it will cause the index to fail.
    3. When we perform expression calculations on index columns in query conditions, we cannot use indexes.
    4. When MySQL encounters a comparison between a string and a number, it will automatically convert the string to a number, and then compare it. If the string is an index column and the input parameter in the conditional statement is a number, then the index column will undergo implicit type conversion. Since the implicit type conversion is implemented through the CAST function, it is equivalent to using a function on the index column, so will cause the index to fail.
    5. To use the joint index correctly, it is necessary to follow the leftmost matching principle, that is, to match the index according to the leftmost first method, otherwise the index will become invalid.
    6. In the WHERE clause, if the conditional column before the OR is an indexed column, but the conditional column after the OR is not an indexed column, the index will fail.

5.5. What is the difference between ${} and #{} in mybatis?

  1. #{}It is precompilation processing and ${}string replacement.
  2. When MyBatis processes , it will replace #{}the in SQL with the number, and use the method of to assign the value;#{}?PreparedStatementset
  3. When MyBatis processes ${}, it replaces ${}with the value of the variable.
  4. Using #{}can effectively prevent SQL injection and improve system security.

5.6. What are the four ACID characteristics of database transactions?

The four characteristics (ACID) of database transactions refer to atomicity (Atomicity), consistency (Consistency), isolation (Isolation), and durability (Durability), which are key factors to ensure the correctness of database operations and data integrity .

  1. Atomicity : All operations in a transaction are either executed successfully or rolled back on failure. That is to say, multiple operations in a transaction must be handled as an indivisible atomic unit, and it is not possible to execute only a part of the operations while giving up other operations. This ensures that the database remains in a consistent state under all circumstances.

  2. Consistency : Before and after a transaction is executed, the state of the database must remain consistent. That is, the database must be in a consistent state when a transaction begins and ends. If an error occurs during transaction execution, the completed operations must be undone so that the data returns to the state before the transaction started.

  3. Isolation : When multiple transactions are executed concurrently, they should be isolated from each other. That is to say, the result of a transaction execution cannot be seen by other transactions until the transaction is committed. This isolation prevents interference between concurrent transactions and ensures that each transaction can execute independently.

  4. Persistence : After a transaction completes, modifications to the database must be persisted permanently. That is to say, after the transaction is committed, the modification to the database should be saved to the disk instead of only in memory. This persistence ensures that modifications are visible to other transactions and to system failures.

5.7 What is the difference between the SSH framework and the SSM framework?

  1. SSH framework: A combination of Spring as the business logic layer framework, Struts2 as the Web layer framework, and Hibernate as the persistence layer framework.
  2. SSM framework: Spring is used as the core framework of the entire application, SpringMVC is used as the web layer framework, and MyBatis is used as a combination of the persistence layer framework.

to be continued:

5.8 spring?

springMVC、gc




Reference articles:
https://blog.csdn.net/Jay112011/article/details/79955593
https://blog.csdn.net/uuqaz/article/details/123502779
https://www.bbsmax.com/A/QV5Z1GoVJy /
https://blog.csdn.net/m0_70051776/article/details/127878918
https://blog.csdn.net/qq_44333980/article/details/126020150
https://javaforall.cn/143988.html
https:// blog.csdn.net/qq_52297656/article/details/127736721

Guess you like

Origin blog.csdn.net/qq_40738764/article/details/127677086