Android, Java knowledge points

I use it to record it myself, it is not very complete, you can refer to it if necessary.

1. Knowledge points

1. Object-oriented understanding and characteristics

Encapsulation, inheritance, polymorphism

Everything is an object.
Encapsulation: Encapsulate objective things into abstract classes, and classes can only allow trusted classes or objects to operate their data and methods, and hide information from untrustworthy ones.

Inheritance: When a class inherits a class, it can use all the functions of the existing class and extend these functions without rewriting the original class.

Polymorphism: The so-called polymorphism means that the same method of a class instance has different manifestations in different situations. Polymorphism enables objects with different internal structures to share the same external interface.

The specific operations of different objects are different, but through a common class, they (those operations) can be called in the same way. For example, the subclass is passed into the parent class parameter, and when the parent class method is called at runtime, the specific internal structure or behavior is determined by the passed in subclass.

The difference between interface and abstract class

Same point

(1) None of them can be instantiated (2) The implementation class of the interface or the subclass of the abstract class can only be instantiated after implementing the methods in the interface or abstract class.

difference

(1) Interfaces only have definitions and cannot have method implementations. In Java 1.8, a default method body can be defined, while abstract classes can have definitions and implementations, and methods can be implemented in abstract classes.

(2) The keyword for implementing the interface is implements, and the keyword for inheriting the abstract class is extends. A class can implement multiple interfaces, but a class can only inherit one abstract class. Therefore, multiple inheritance can be achieved indirectly using interfaces.

(3) Interfaces emphasize the implementation of specific functions, while abstract classes emphasize ownership relationships.

(4) Interface member variables default to public static final, must be assigned an initial value, and cannot be modified; all its member methods are public and abstract. Member variables in abstract classes default to default and can be redefined in subclasses or reassigned; abstract methods are modified by abstract and cannot be modified by private, static, synchronized, native, etc., and must end with a semicolon without a flower. brackets.

2、Final

(1) Modified class
When a class is modified with final, it indicates that this class cannot be inherited.
 When using final to modify a class, you should choose carefully. Unless the class really will not be used for inheritance in the future or for security reasons, try not to design the class as a final class.

(2) Modification method
final modifies a method and cannot be overridden
. "There are two reasons for using the final method. The first reason is to lock the method to prevent any inherited class from modifying its meaning ; the second reason is efficiency. In earlier Java implementations, final methods were converted into inline calls. However, if the method is too large, you may not see any performance improvement from inline calls. In recent Java versions, there is no need to use final methods These optimizations are made."
Therefore, if you want to explicitly prohibit the method from being overridden in subclasses, you should only make the method final.
  Note: private methods of a class are implicitly designated as final methods.

(3) Modified variables
For a final variable, if it is a variable of a basic data type, its value cannot be changed once it is initialized (it must be initialized); if it is a variable of a reference type, it cannot be changed after it is initialized. It points to another object.

3. Thread synchronization method

For multi-threaded programs, synchronization refers to allowing only one thread to access a certain resource within a certain period of time.

(1) Mutex lock
Mutex lock is the most common thread synchronization method. It is a special variable. It has two states: lock and unlock. Once acquired, it will be locked and can only be unlocked by this thread. During this period, other threads cannot obtain it.
Thread synchronization can be achieved by locking the same resource before using it and unlocking it after use. It should be noted that if you do not unlock the resource after locking, it will cause a deadlock.

(2) Read-write lock
If the read-write lock is in a write-locked state, all threads trying to lock will be blocked before unlocking.
If the read-write lock is in the read-locked state, all threads trying to lock in read mode can obtain access rights, but threads locked in write mode will be blocked;

(3) Semaphore
It allows multiple threads to access the same resource at the same time, but it needs to limit the maximum number of threads that can access this resource at the same time.

(4) Condition variable:
When the thread is waiting for certain conditions to be met, the thread enters sleep state. Once the conditions are met, it wakes up. This way it does not occupy the precious mutex object lock and achieves high efficiency.

4、volatile

Variables modified with volatile are visible to all threads.

5. The internal structure of ArrayList is different from LinkList

(1).ArrayList implements a data structure based on dynamic arrays, and LinkedList implements a data structure based on linked lists.
(2). For random access to get and set, ArrayList is better than LinkedList, because ArrayList can be positioned randomly, while LinkedList needs to move the pointer to the node step by step. (Refer to arrays and linked lists to think)
(3). For new and deleted operations add and remove, LinedList is more advantageous. It only needs to modify the pointer, while ArrayList needs to move data to fill the space of the deleted object.

6. Class objects, instance objects

(1) Class object: the class itself
(2) Instance object: the object instantiated by the class

7. Static variables and instance variables

(1) Static variables: Static variables are also called class variables. Variables that are independent of methods are modified by static.
Static variables do not belong to an instance object, but to the entire class. As long as the program loads the bytecode of the class, the static variables will be allocated space without creating any instance objects, and the static variables can be used.

(2) Instance variables: Instance variables are also independent of variables outside of methods, but are not modified by static.
Instance variables belong to the properties of an object. An instance object must be created before the instance variable in it will be allocated space and this instance variable can be used.

8. Shallow copy and deep copy

(1) Shallow copy: Add a pointer to an existing memory address
(2) Deep copy: Add a pointer and apply for a new memory, so that the added pointer points to the new memory

9、HashMap

10. Multi-threading related

A thread refers to a single sequential control flow in a process. Multiple threads can run concurrently in a process, and each thread performs different tasks in parallel.

Multithreading is a special form of multitasking, but multithreading uses a smaller resource overhead.
Process: A process consists of memory space allocated by the operating system and contains one or more threads. A thread cannot exist independently, it must be part of the process. A process runs until all non-daemon threads have finished running.

Multi-threading allows programmers to write efficient programs to fully utilize the CPU.

11. JVM memory model and class loading mechanism.

12. OOM exception related

Memory overflow: the currently occupied memory + requested memory resources exceed the maximum memory of the Dalvik virtual machine. Memory
jitter: a large number of objects are created in a short period of time and then released again, triggering a GC
memory leak: objects in the process are not referenced, but are indirectly referenced to other objects. , so that GC cannot act on it

(1) Heap memory overflow

Heap memory is used to store object instances. As long as objects are continuously created and there are reachable paths between GC Roots and objects to avoid garbage collection, the number of objects will soon appear after exceeding the maximum heap size limit.

(2) Method area and metaspace overflow

(3) Direct memory overflow:
Direct memory is not part of the data area when the virtual machine is running, and is not limited by heap memory, but is limited by the machine memory size. Commonly, for example, in NIO, you can use native functions to directly allocate off-heap memory, which can easily lead to OOM problems.

(4) Stack memory overflow
The stack is private to the thread, and its life cycle is the same as that of the thread. When each method is executed, a stack frame will be created to store local variable table, operand stack, dynamic link, method exit and other information. The process of method calling is the process of pushing and popping the stack frame.

In the Java virtual machine specification, two exceptions are defined for the virtual machine stack:

If the stack depth requested by the thread is greater than the depth allowed by the virtual machine, a StackOverflowError exception will be thrown.
If the virtual machine stack can be dynamically expanded and sufficient memory cannot be applied for during expansion, an OutOfMemoryError exception will be thrown.

13. Design pattern

Singleton mode, constructor mode, chain of responsibility mode
(1) singleton mode
can only have one instance of itself

//懒汉式单例类 
public class Sing {
    private Sing() {}
    private static Sing s=null;
    //静态工厂方法 
    public static Sing getInstance() {
         if (s == null) {  
             s = new Sing();
         }  
        return s;
    }
}

(2) Constructor pattern
(3) Chain of responsibility pattern
A chain of receiver objects is created for the request. In this pattern, usually each receiver contains a reference to another receiver. If an object cannot handle the request, then it passes the same request to the next recipient, and so on.
For example: OkHttp uses the chain of responsibility model to create an interceptor chain when processing network requests. Whenever an interceptor is executed, the next interceptor will be called or the result will be returned without calling it.

This order is controlled because there is an index parameter in the method parameter of new RealInterceptorChain. Each time in the method, index+1 will be used to call the next interceptor in sequence.
Insert image description here
(4) State mode.
The behavior of a class changes based on its state.
(5) Template mode
: Extract public methods and put them in template classes. Subclasses inherit
, encapsulate and expand the unchanged parts.

14. The difference between Java heap, stack and queue

Stack: First in, last out, with memory capability, used for bracket solving
Queue: First in, first out, for sequential processing, such as the management of various resources in a computer system

The system generally divides two different memory spaces in the memory, one is Stack (stack) and the other is heap (heap)

Their main differences are:

The stack has a structure, and each block is stored in a certain order, so the size of each block can be clearly known; the heap has no structure, and data can be stored arbitrarily. Therefore, stack addressing is faster than heap.

Each thread allocates a stack, and each process allocates a heap, that is, the stack is exclusive to the thread, and the heap is shared by the thread.

15. Five states of threads

(1) New : new Thread()

(2) Ready : "executable state", thread.start()

(3) Running : The thread obtains CPU permissions for execution, and the thread can only move from ready to running.

(4) Blocking : The thread gives up the right to use the CPU for some reason and temporarily stops running. There are three situations:
(01) Waiting for blocking – By calling the thread’s wait() method, the thread waits for the completion of a certain work.
(02) Synchronous blocking - the thread fails to acquire the synchronized synchronization lock (because the lock is occupied by other threads), it will enter the synchronous blocking state.
(03) Other blocking - When calling the thread's sleep() or join() or issuing an I/O request, the thread will enter the blocked state. When the sleep () state times out, the join () waits for the thread to terminate or time out, or when the I/O processing is completed, the thread is transferred to the ready state again.

(5) Death : The thread completes execution or exits the run() method due to an exception, and the thread ends its life cycle.

16. The difference between String, StringBuffer and StringBuilder

String: immutable string
StringBuffer: variable string, low efficiency, thread-safe
StringBuilder: variable character sequence, high efficiency, thread-safe

String is a string constant, while StringBuilder and StringBuffer are both string variables, that is, once the String object is created, the object cannot be changed, but the latter two can be modified multiple times without generating new unused objects.

Common: s=s+"aa";
This actually means that the JVM creates a new object called s, and assigns the original s plus "aa" to the new s. s has not actually been changed, so Java The operation on the String object is actually a process of constantly creating new objects and recycling old objects, so the execution speed is very slow.

The biggest difference between the StringBuilder class and StringBuffer is that StringBuilder's methods are not thread-safe (cannot be accessed synchronously).

Since StringBuilder has a speed advantage over StringBuffer, it is recommended to use the StringBuilder class in most cases. However, in the case where the application requires thread safety, the StringBuffer class must be used.

17. What is the difference between array and linked list? What data structures in Java are implemented using them?

(1) The memory space of the array is continuous. The array size will be specified when the array is created, and the size of the array cannot be dynamically changed because continuous fixed memory space has been allocated during creation, and each element occupies two bytes. .

The random access speed of the array is fast, and the addition and deletion efficiency is low.
The addition and deletion of the linked list is highly efficient, and the linked list has strong scalability

18. Overloading and rewriting

(1) Overloading: The method name remains unchanged, but the return value and parameters change
(2) Overwriting: The subclass inherits the parent class, and rewrites the method content inherited from the parent class.

19. Database index structure

20. Why is String modified by final?

The String class is modified with the final keyword, which means that String cannot be inherited
for thread safety.

21. Int and Integer

Integer is the wrapper class of int; int is the basic data type;
Integer variables must be instantiated before they can be used; int variables are not required;
Integer is actually a reference to the object, pointing to this new Integer object; int directly stores data values;
Integer The default value is null; the default value for int is 0.

Integer can distinguish the difference between unassigned and value 0, while int cannot express the unassigned situation

22. The difference between synchronized modified static methods and ordinary methods

Synchronized has a synchronization function and is a kind of mutex, which locks the object. When synchronized modifies ordinary methods, the lock object is this object. When modifying a static method, the lock object is a bytecode file object.

Disadvantages of synchronized:
1. The bottom layer of synchronized is implemented by jvm, so the release of the lock cannot be controlled manually and is not as flexible as lock. Once an exception occurs in the synchronized modified method, jvm guarantees that the lock will be released (the lock needs to be released in finally).
2. Synchronized is an unfair lock and does not guarantee fairness.

The keyword synchronized can ensure that only one thread can execute a certain method or a certain code block at the same time (mainly operations on shared data in the method or code block).
synchronized can also ensure that changes in one thread (mainly changes in shared data) are seen by other threads (to ensure visibility, it can completely replace the volatile function, but volatile is more lightweight and should be used in different scenarios)

synchronized includes three usages:
modifying instance methods,
modifying static methods,
and modifying code blocks

22. The difference between processes and threads

Address space: Threads share the address space of the process, while processes have independent address spaces.

Resources: Threads share the resources of this process, such as memory, I/O, CPU, etc., which is not conducive to resource management and protection. However, the resources between processes are independent and can be well managed and protected.

Robustness: Multi-process is more robust than multi-thread. After one process crashes, it will not affect other processes in protected mode, but if one thread crashes, the entire process will die.

Execution process:
Each independent process has an entry point for program running, a sequential execution sequence and a program entry point, which results in high execution overhead. However, threads cannot be executed independently and must exist in the application program. The application program provides execution control of multiple threads and has low execution overhead.

Concurrency:
Both can be executed concurrently.

When switching:
When the process is switched, it consumes a lot of resources and has high efficiency. So when it comes to frequent switching, it is better to use threads than processes. Similarly, if concurrent operations that are required to be performed at the same time and share certain variables, only threads cannot be used.

23. SharePreference principle and cross-process data sharing issues

SharedPreferences is a means of data persistence provided by Android, which is suitable for single-process and small-batch data storage and access. Because the implementation of SharedPreferences is based on a single xml file, and all persistent data is loaded into memory at one time, if the data is too large, it is not suitable to use SharedPreferences for storage. The same reason applies to single-process scenarios. Since Android's native file access does not support multi-process mutual exclusion, SharePreferences does not support it either. If multiple processes update the same xml file, there may be a mutual exclusion problem. .

2. Algorithm

1. Flip singly linked list

public class Main {

    public static void main(String[] args) {
        Node head=new Node(0);
        Node n1=new Node(1);
        Node n2=new Node(2);
        Node n3=new Node(3);

        head.setNext(n1);n1.setNext(n2);n2.setNext(n3);

        //打印反转前的
        System.out.println("反转前的链表:");
        Node h=head;
        while (h!=null){
            System.out.println(h.getData()+" ");
            h=h.getNext();
        }
        
//        System.out.println("递归(从后向前)反转后的链表:");
//        head=Reversel(head);
//        while (head!=null){
//            System.out.println(head.getData()+" ");
//            head=head.getNext();
//        }

        System.out.println("从前向后反转后的链表:");
        head=Reversel2(head);
        while (head!=null){
            System.out.println(head.getData()+" ");
            head=head.getNext();
        }

    }

    /**
     * 递归方式反转链表
     * @param head
     * @return
     * 从后向前依次反转
     */
    public static Node Reversel(Node head){
        if (head==null||head.getNext()==null){
            return head;
        }
        Node reHead=Reversel(head.getNext());//先反转后面的
        head.getNext().setNext(head);//将当前结点的指针域指向前一结点
        head.setNext(null);//前一结点的指针域为null
        return reHead;//反转后新链表的头结点
    }

    /**
     * 遍历方式反转链表
     * @param head
     * @return
     * 从前往后一次调换指针方向
     */
    public static Node Reversel2(Node head){
        if (head==null){
            return head;
        }
        Node pre=head;
        Node cur=head.getNext();
        Node temp;
        while (cur!=null){
            temp=cur.getNext();
            cur.setNext(pre);//反转结点的指针域指向上一个结点
            //指针向下移动
            pre=cur;
            cur=temp;
        }
        head.setNext(null);
        return pre;
    }

}
class Node{
    private int data;
    private Node next;
    public Node(int data){
        this.data=data;
    }
    public int getData() {
        return data;
    }
    public void setData(int data) {
        this.data = data;
    }
    public Node getNext() {
        return next;
    }
    public void setNext(Node next) {
        this.next = next;
    }
}

2. Determine whether there are duplicate elements in the array

Selection sort: Select elements from the beginning as the index, select the largest or smallest element value among the unsorted elements in the future, and replace it with the index value, and so on, until all elements are sorted.

//先选择排序,再判断相邻元素是否有重叠
public static boolean judge(int[] a){
    for (int j=0;j<a.length-1;j++){
         int temp=j;
         for (int k=j+1;k<a.length;k++){
             if (a[k]<a[temp]){
                 temp=k;
             }
         }
         int t=a[j];
         a[j]=a[temp];
         a[temp]=t;
     }
     boolean result=false;
     for (int j=0;j<a.length-1;j++){
         if (a[j+1]==a[j]){
             result=true;
             break;
         }
     }
     return result;
 }

3. Determine whether the singly linked list has a cycle

import java.util.Scanner;

public class Main {

    public static void main(String[] args){
        //建了一个循环链表
        Node n1=new Node(5);Node n2=new Node(2);Node n3=new Node(10);Node n4=new Node(7);
        n1.next=n2;n2.next=n3;n3.next=n4;n4.next=n2;
        System.out.println(isCircle(n1));
    }
    //从头结点出发 判断快慢指针所指的数据是否环
    public static boolean isCircle(Node head) {
        Node p1=head;
        Node p2=head;
        while (p2.next!=null&&p2.next.next!=null){
            p1=p1.next;
            p2=p2.next.next;
            if (p1==p2){
                return true;
            }
        }
        return false;
    }
}
class Node{
    int data;
    Node next;
    Node(int data){
        this.data=data;
    }
}

4. Find the nearest common parent node of any two nodes in the binary tree

Guess you like

Origin blog.csdn.net/qq_46269365/article/details/120999153