Chapter 1 Basics-Java source notes

1 String, Long source code analysis

1.1 String

  • Immutability stems from the String class and the class attribute value [] are all modified with final. The class cannot be inherited, and its memory address cannot be modified after property assignment.
  • The character string is garbled , and the string is converted into binary. Due to the default encoding of different systems, garbled characters appear. The solution is to specify the encoding.
  • Capitalization of the first letter , name.substring (0, 1) .toLowerCase () + name.substring (1); name.substring (0, 1) .toUpperCase () + name.substring (1).
  • Equality judgment , the methods are equals () and equalsIgnoreCase (), judge whether two Strings are matched, and judge whether characters are equal one by one.
  • Replace, delete , replace, replaceAll and replaceFirst.
  • Split and merge , Splitter and Joiner of Guava tools.

1.2 Long

  • Caching problem
    Cached from -128 to 127. If it is a value in this range, take the value from here. Internal static class cache data.
private static class LongCache {
    private LongCache(){}
    // 缓存,范围从 -128 到 127,+1 是因为有个 0
    static final Long cache[] = new Long[-(-128) + 127 + 1];

    // 容器初始化时,进行加载
    static {
        // 缓存 Long 值,注意这里是 i - 128 ,所以再拿的时候就需要 + 128
        for(int i = 0; i < cache.length; i++)
            cache[i] = new Long(i - 128);
    }
}

1.3 Interview

  • 3.1 When using Long, we recommend using the valueOf method more and less using the parseLong method.
    Answer: Because Long itself has a caching mechanism, the Long in the range of -128 to 127 is cached. The valueOf method will get the value from the cache. If it hits the cache , Will reduce the resource overhead, parseLong method does not have this mechanism.

2 Java commonly used keywords

2.1 static

Static, modify class variables, methods, method blocks. Static class variables need to pay attention to concurrent security issues.
Initialization timing

public class Parent {
    public static List<String> PARENT_LIST = new ArrayList() {{
        System.out.println("parent 静态变量初始化");
    }};

    static {
        System.out.println("parent 静态代码块初始化");
    }

    public Parent(){
        System.out.println("parent 构造器初始化");
    }

    public void testStatic(){
        System.out.println("parent 静态方法执行");
    }
}

public class Son extends Parent {
    public static List<String> LIST = new ArrayList() {{
        System.out.println("son 静态变量初始化");
    }};

    static {
        System.out.println("son 静态代码块初始化");
    }

    public Son() {
        System.out.println("son 构造器初始化");
    }

    public void testSonStatic(){
        System.out.println("son 静态方法执行");
    }

    public static void main(String[] args) {
        System.out.println("main 执行");
        new Son();
    }
}

Print result:
parent static variable initialization
parent static code block initialization
son static variable initialization
son static code block initialization
main execute
parent constructor initialization
son constructor initialization
conclusion

  • Parent class static variables and static code blocks are initialized before child classes;
  • Static variables and static code blocks are initialized before constructors;
  • The parent class constructor takes precedence over the child class initialization.

2.2 final

  • Classes modified by final cannot be inherited;
  • A method modified by final means that the method cannot be overwritten;
  • A variable modified by final means that the variable must be initialized when declared, and the memory address cannot be changed. Note that the memory address cannot be changed, not the value. For objects such as List and Map, the value can be changed.

2.3 try catch finally

public class TryCatchFinally {
    public static void main(String[] args) {
        TryCatchFinally tryCatchFinally = new TryCatchFinally();
        tryCatchFinally.test();
    }

    public void test(){
        try {
            System.out.println("log try");
            if (true) {
                throw new RuntimeException("try exception");
            }
        } catch (Exception e) {
            System.out.println("log catch");
            if (true) {
                throw new RuntimeException("catch exception");
            }
        } finally {
            System.out.println("log finally");
        }
    }
}

结果
og try
log catch
log finally
Exception in thread “main” java.lang.RuntimeException: catch exception

  • finally execute first, then throw an exception;

2.4 volatile

Volatile, English explanation: Likely to change suddenly and unexpectedly, especially by getting worse, meaning volatile. Used to share decorated variables.
** Underlying principle: ** When multiple threads are executed on multiple CPUs separately, in order to speed up, the thread does not read the shared variable from the memory, but from the CPU cache, then there is a problem when the thread a change when the value of the variable X, due to the presence of cpu cache, thread B does not know the variable X has been modified, which leads to inconsistent variable X value problem .
Solution: Modify the variable X with volatile. When the thread A changes the value of the variable X, the memory will notify other CPUs that the variable X of its cpu cache is invalid, and other threads read the variable X from the memory again to ensure data consistency.
Insert picture description here

2.5 transient

Modified class variable means that this variable is ignored when the class is serialized.

2.6 default

Used to modify the interface method, indicating that the method subclass is invalid, but the interface must have a default implementation.

public interface ParentInterface {
    default void testMy() {
        System.out.println("do something");
    }
}

2.7 Interview questions

  1. How to prove that static variables are not related to classes?
  • No need to initialize the class, you can use static variables directly;
  • Write the main method in the class, even if the code of the class is not initialized, the static variables will be automatically initialized;
  • Static variables are only initialized once, and no matter how many classes are new, static variables are initialized only once.

3 Arrays, Collections, Objects common method source code analysis

3.1 General features of tools

  1. The constructor is private, no need to new out;
  2. Methods are usually modified by static and final.

3.2 Arrays

Arrays are mainly used to deal with arrays, such as sorting, searching, filling, etc.

3.2.1 Sort

Support a lot of parameter types, come to a demo:

package demo.two;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableList;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

@Slf4j
public class MyArraysDemoTest {
    @Test
    public void testSort() {
        List<MySort> list = ImmutableList.of(
                new MySort("100"),
                new MySort("200"),
                new MySort("600"),
                new MySort("220"),
                new MySort("150")
        );
        MySort[] mySorts = new MySort[list.size()];
        list.toArray(mySorts);
        log.info("before mySorts={}", JSON.toJSONString(mySorts));
        Arrays.sort(mySorts, Comparator.comparing(MySort::getValue));
        log.info("after mySorts={}", JSON.toJSONString(mySorts));
    }

    @Data
    class MySort {
        private String value;
        public MySort(String value) {
            this.value = value;
        }
    }

}

3.2.2 Binary search

Insert picture description here

3.2.3 Copy

copyOf (), copyOfRange () (partial copy).

3.3 Collections

Tools used by the collection.

3.3.1 Find the maximum and minimum

Collections.max () and min () methods.
Insert picture description here
Special: <T extends Object & Comparable <? Super T >> means that T is required to inherit the Object class and implement the Comparable interface.

3.3.2 Multiple types of collections

There are thread-safe collections (Synchronized at the beginning) and immutable collections (Unmodifiable at the beginning), see the underlying implementation.
Insert picture description here
Insert picture description here
You can see that the operations are locked.
An immutable collection is a new collection from the original collection, which can only be read but not written.
Insert picture description here

3.4 Objects

Mainly used for judging equality and judging empty.

3.4.1 Equality judgment

Objects provides equals and deepEquals two methods for equality judgment, the former is to determine the basic types and custom classes, the latter is used to determine the array.

3.4.2 Judgement

Objects provides various judgments about null. IsNull and nonNull return Boolean value for whether the object is null. The requireNonNull method is more strict. If it is null, an exception will be thrown directly.

Published 97 original articles · praised 3 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_39530821/article/details/105084269