11: Common class

01. String related classes

1.1 overview of String class

import org.junit.Test;

/**
 * String Use of
 */
public class StringTest {

    /**
     * String:String, represented by a pair of "".
     * 1.String Declared final and cannot be inherited
     * 2.String The Serializable interface is implemented: it means that the string supports serialization.
     *         The Comparable interface is implemented: it means that strings can compare sizes
     * 3.String final char[] value is internally defined to store string data
     * 4.String:Represents an immutable character sequence. Abbreviation: non variability.
     *      reflect:
     *
     */
    @Test
    public void Test1(){

    }
}

1.2. Understand the immutability of String

import org.junit.Test;

/**
 * String Use of
 */
public class StringTest {

    /**
     * String:String, represented by a pair of "".
     * 1.String Declared final and cannot be inherited
     * 2.String The Serializable interface is implemented: it means that the string supports serialization.
     *         The Comparable interface is implemented: it means that strings can compare sizes
     * 3.String final char[] value is internally defined to store string data
     * 4.String:Represents an immutable character sequence. Abbreviation: non variability.
     *      Embodiment: 1. When the string is re assigned, the assigned memory area needs to be rewritten, and the original value cannot be used for assignment.
     *           2.When connecting an existing string, you also need to assign a value to the memory area again. The original value cannot be used for assignment.
     *           3.When calling the replace() method of String to modify the specified character or String, you also need to reassign the memory area assignment, and the original value cannot be used for assignment.
     * 5.A string is assigned a literal value (different from new), and the string value is declared in the string constant pool.
     * 6.Strings with the same content will not be stored in the string constant pool.
     *
     */
    @Test
    public void Test1(){
        String s1 = "abc";  //Definition of literal quantity
        String s2 = "abc";
        s1 = "hello";

        System.out.println(s1 == s2);//Compare the address values of s1 and s2

        System.out.println(s1);//hello
        System.out.println(s2);//abc

        System.out.println("*********************");

        String s3 = "abc";
        s3 += "def";
        System.out.println(s3);//abcdef

        System.out.println("**********************");

        String s4 = "abc";
        String s5 = s4.replace('a', 'm');
        System.out.println(s4);//abc
        System.out.println(s5);//mbc
    }
}

1.3 comparison of different instantiation methods of String

1. Creation of String object

String str = "hello";

//In essence, this.value = new char[0];
String  s1 = new String(); 

//this.value = original.value;
String  s2 = new String(String original); 

//this.value = Arrays.copyOf(value, value.length);
String  s3 = new String(char[] a);

String  s4 = new String(char[] a,int startIndex,int count);


2,String str1 = “abc”; And String str2 = new String("ABC"); What's the difference?

  • String constants are stored in the string constant pool for sharing
  • String non constant objects are stored in the heap.

3. Practice

import org.junit.Test;

/**
 * String Use of
 */
public class StringTest {

    /**
     * String Instantiation method of
     * Method 1: defined by literal quantity
     * Mode 2: through the new + constructor
     *
     * Interview question: String s = new String("abc"); How many objects are created in memory?
     *      Two: one is the new structure in the heap space, and the other is the data in the constant pool corresponding to char []: "abc"
     *
     */
    @Test
    public void test2(){
        //Through literal definition: at this time, the data javaEE of s1 and s2 is declared in the string constant pool in the method area.
        String s1 = "javaEE";
        String s2 = "javaEE";

        //Through the new + constructor: the address values saved in s3 and s4 at this time are the corresponding address values after the data opens up space in the heap space.
        String s3 = new String("javaEE");
        String s4 = new String("javaEE");

        System.out.println(s1 == s2);//true
        System.out.println(s1 == s3);//false
        System.out.println(s1 == s4);//false
        System.out.println(s3 == s4);//false

        System.out.println("***********************");
        Person p1 = new Person("Tom",12);
        Person p2 = new Person("Tom",12);

        System.out.println(p1.name.equals(p2.name));//true
        System.out.println(p1.name == p2.name);//true

        p1.name = "Jerry";
        System.out.println(p2.name);//Tom
    }
}

Person class

/**
 * @author subei
 * @create 2020-05-09 11:20
 */
public class Person {

    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person() {

    }
}

1.4 comparison of different splicing operations of String

import org.junit.Test;

/**
 * String Use of
 */
public class StringTest {

    /**
     * conclusion
     *     1.The splicing results of constants and constants are in the constant pool. And constants with the same content will not exist in the constant pool.
     *     2.As long as one of them is a variable, the result is in the heap
     *     3.If the result of splicing calls the intern() method, the return value is in the constant pool
     *
     */
    @Test
    public void test4(){
        String s1 = "javaEEhadoop";
        String s2 = "javaEE";
        String s3 = s2 + "hadoop";
        System.out.println(s1 == s3);//false

        final String s4 = "javaEE";//s4: constant
        String s5 = s4 + "hadoop";
        System.out.println(s1 == s5);//true

    }

    @Test
    public void test3(){
        String s1 = "javaEE";
        String s2 = "hadoop";

        String s3 = "javaEEhadoop";
        String s4 = "javaEE" + "hadoop";
        String s5 = s1 + "hadoop";
        String s6 = "javaEE" + s2;
        String s7 = s1 + s2;

        System.out.println(s3 == s4);//true
        System.out.println(s3 == s5);//false
        System.out.println(s3 == s6);//false
        System.out.println(s5 == s6);//false
        System.out.println(s3 == s7);//false
        System.out.println(s5 == s6);//false
        System.out.println(s5 == s7);//false
        System.out.println(s6 == s7);//false

        String s8 = s5.intern();//Return the "Java EE Hadoop" that already exists in the constant value used by s8
        System.out.println(s3 == s8);//true
    }
}

1.4.1. String usage trap

1, String s1 = "a";

Description: a string with literal "a" is created in the string constant pool.

2, s1 = s1 + "b";

Note: in fact, the original "a" string object has been discarded, and now a string s1 + "b" (i.e. "ab") is generated in the heap space. If these operations to change the string content are performed multiple times, a large number of duplicate string objects will be stored in memory and reduce efficiency. If such operations are put into the loop, the performance of the program will be greatly affected.

3, String s2 = "ab";

Description: directly create a string with literal "ab" in the string constant pool.

4, String s3 = "a" + "b";

Description: s3 refers to the string of "ab" that has been created in the string constant pool.

5, String s4 = s1.intern();

Note: s1 object in heap space will assign the existing "ab" string in constant pool to s4 after calling intern().

6. Practice

1.5. An interview question in String

/**
 * An interview question
 */
public class StringTest {
    String str = new String("good");
    char[] ch = { 't', 'e', 's', 't' };

    public void change(String str, char ch[]) {
        str = "test ok";
        ch[0] = 'b';
    }
    public static void main(String[] args) {
        StringTest ex = new StringTest();
        ex.change(ex.str, ex.ch);
        System.out.println(ex.str);//good
        System.out.println(ex.ch);//best
    }
}

1.6 memory structure involving strings in JVM












1.7 common methods of String 1

import org.junit.Test;

public class StringMethodTest {

    /**
     * int length(): Length of returned string: return value.length
     * char charAt(int index): Returns the character at an index. return value[index]
     * boolean isEmpty(): Judge whether it is an empty string: return value.length==0
     * String toLowerCase(): Converts all characters in a String to lowercase using the default locale
     * String toUpperCase(): Converts all characters in a String to uppercase using the default locale
     * String trim(): Returns a copy of a string, ignoring leading and trailing whitespace
     * boolean equals(Object obj): Compare whether the contents of the string are the same
     * boolean equals IgnoreCase(String anotherString): Similar to the equals method, case is ignored
     * String concat(String str): Concatenates the specified string to the end of this string. Equivalent to "+"
     * int compareTo(String anotherString): Compare the size of two strings
     * String substring(int beginIndex): Returns a new string, which is the last substring of the string intercepted from beginIndex.
     * String substring(int beginIndex,int endIndex): Returns a new string, which is a substring intercepted from beginIndex to endindex (not included).
     */
    @Test
    public void test2(){
        String s1 = "HelloWorld";
        String s2 = "helloworld";
        System.out.println(s1.equals(s2));//false
        System.out.println(s1.equalsIgnoreCase(s2));//true
        
        String s3 = "abc";
        String s4 = s3.concat("def");
        System.out.println(s4);//abcdef

        String s5 = "abc";
        String s6 = new String("abe");
        System.out.println(s5.compareTo(s6));//-2 / / the sorting of strings is involved

        String s7 = "It's so noisy around";
        String s8 = s7.substring(2);
        System.out.println(s7);
        System.out.println(s8);

        String s9 = s7.substring(0, 2);
        System.out.println(s9);
    }

    @Test
    public void Test1(){
        String s1 = "helloworld";
        System.out.println(s1.length());
        System.out.println(s1.length());
        System.out.println(s1.charAt(0));
        System.out.println(s1.charAt(9));
//        System.out.println(s1.charAt(10));
//        s1 = "";
        System.out.println(s1.isEmpty());

        String s2 = s1.toLowerCase();
        System.out.println(s1);//s1 is immutable and remains the original string
        System.out.println(s2);//String after lowercase

        String s3 = "   he  llo   world   ";
        String s4 = s3.trim();
        System.out.println("-----" + s3 + "-----");
        System.out.println("-----" + s4 + "-----");
    }

}

1.8 common methods of String 2

import org.junit.Test;

public class StringMethodTest {

    /**
     * boolean endsWith(String suffix): Tests whether this string ends with the specified suffix
     * boolean startsWith(String prefix): Tests whether this string starts with the specified prefix
     * boolean startsWith(String prefix, int toffset): Tests whether the substring of this string starting from the specified index starts with the specified prefix
     *
     * boolean contains(CharSequence s): Returns true if and only if this string contains the specified sequence of char values
     * int indexOf(String str): Returns the index of the specified substring at the first occurrence in this string
     * int indexOf(String str, int fromIndex): Returns the index of the specified substring at the first occurrence in this string, starting from the specified index
     * int lastIndexOf(String str): Returns the index of the rightmost occurrence of the specified substring in this string
     * int lastIndexOf(String str, int fromIndex): Returns the index of the last occurrence of the specified substring in this string, and searches backwards from the specified index
     *
     * Note: indexOf and lastIndexOf methods return - 1 if they are not found
     */
    @Test
    public void test3(){
        String str1 = "helloworld";
        boolean b1 = str1.endsWith("rld");
        System.out.println(b1);

        boolean b2 = str1.startsWith("He");
        System.out.println(b2);

        boolean b3 = str1.startsWith("ll",2);
        System.out.println(b3);

        String str2 = "wor";
        System.out.println(str1.contains(str2));

        System.out.println(str1.indexOf("lo"));

        System.out.println(str1.indexOf("lo",5));

        String str3 = "hellorworld";

        System.out.println(str3.lastIndexOf("or"));
        System.out.println(str3.lastIndexOf("or",6));

        //When does indexOf(str) and lastIndexOf(str) return the same value?
        //Case 1: there is a unique str. case 2: there is no str
    }
}

1.9 common methods of String 3

import org.junit.Test;

public class StringMethodTest {

    /**
     * Replace:
     * String replace(char oldChar, char newChar): Returns a new string obtained by replacing all oldchars that appear in this string with newChar.
     * String replace(CharSequence target, CharSequence replacement): Replaces all substrings of this string that match the literal target sequence with the specified literal replacement sequence.
     * String replaceAll(String regex, String replacement): Replace all substrings of this string that match the given regular expression with the given replacement.
     * String replaceFirst(String regex, String replacement): Replace this string with the given replacement to match the first substring of the given regular expression.
     *
     * Match:
     * boolean matches(String regex): Tells whether this string matches the given regular expression.
     *
     * section:
     * String[] split(String regex): Splits the string based on the match of the given regular expression.
     * String[] split(String regex, int limit): Split the string according to the regular expression matching the given string. The maximum number is no more than limit. If it exceeds, all the rest will be placed in the last element.
     *
     */
    @Test
    public void test4(){
        String str1 = "Welcome to Potala Palace, Tibet";
        String str2 = str1.replace('west','east');

        System.out.println(str1);
        System.out.println(str2);

        String str3 = str1.replace("Beijing", "Nanjing");
        System.out.println(str3);

        System.out.println("*************************");
        String str = "12hello34world5java7891mysql456";
        //Replace the number in the string with,, and remove it if there are at the beginning and end of the result
        String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", "");
        System.out.println(string);

        System.out.println("*************************");
        str = "12345";
        //Judge whether all str strings are composed of numbers, that is, 1-n numbers
        boolean matches = str.matches("\\d+");
        System.out.println(matches);
        String tel = "0571-4534289";
        //Judge whether this is a fixed line telephone in Hangzhou
        boolean result = tel.matches("0571-\\d{7,8}");
        System.out.println(result);

        System.out.println("*************************");
        str = "hello|world|java";
        String[] strs = str.split("\\|");
        for (int i = 0; i < strs.length; i++) {
            System.out.println(strs[i]);
        }
        System.out.println();
        str2 = "hello.world.java";
        String[] strs2 = str2.split("\\.");
        for (int i = 0; i < strs2.length; i++) {
            System.out.println(strs2[i]);
        }
    }
}

1.10 conversion between String and basic data type packing class

import org.junit.Test;

/**
 * It involves the conversion between String class and other structures
 */
public class StringTest1 {

    /**
     * review
     *    String Conversion with basic data type and wrapper class
     *
     *    String --> Basic data type and wrapper class: call the static method of wrapper class: parseXxx(str)
     *    Basic data type, wrapper class -- > String: call valueOf(xxx) overloaded by String
     */
    @Test
    public void test1(){
        String str1 = "123";
//        int num = (int)str1;// FALSE
        int num = Integer.parseInt(str1);

        String str2 = String.valueOf(num);   //"123
        String str3 = num + "";

        System.out.println(str1 == str3);   //false
    }

}

1.11 conversion between String and char []

import org.junit.Test;

/**
 * It involves the conversion between String class and other structures
 */
public class StringTest1 {

    /**
     * String Conversion between and char []
     *
     * String --> char[]:Call toCharArray() of String
     * char[] --> String:Call the constructor of String
     */
    @Test
    public void test2(){
        String str1 = "abc123"; //Title: a21cb3

        char[] charArray = str1.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            System.out.println(charArray[i]);
        }

        char[] arr = new char[]{'h','e','l','l','o'};
        String str2 = new String(arr);
        System.out.println(str2);
    }
}

1.12 conversion between String and byte []

import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * It involves the conversion between String class and other structures
 */
public class StringTest1 {

    /**
     * String Conversion between and byte []
     *
     * Code: String -- > byte []: call getBytes() of string
     * Decoding: byte [] -- > String: call the constructor of String
     *
     * Encoding: String -- > bytes (readable -- > incomprehensible binary data)
     * Decoding: inverse process of encoding, byte -- > string (incomprehensible binary data -- > understandable)
     *
     * Note: during decoding, the character set used for decoding must be consistent with the character set used for encoding, otherwise garbled code will appear.
     *
     */
    @Test
    public void test3() throws UnsupportedEncodingException {
        String str1 = "abc123 heavy industry";
        byte[] bytes = str1.getBytes();//Use the default character encoding set for conversion
        System.out.println(Arrays.toString(bytes));

        byte[] gbks = str1.getBytes("gbk");//Use gbk character set for encoding.
        System.out.println(Arrays.toString(gbks));

        System.out.println("*****************************");

        String str2 = new String(bytes);//Decode using the default character set.
        System.out.println(str2);

        String str3 = new String(gbks);
        System.out.println(str3);//Garbled code. Cause: the encoding set and decoding set are inconsistent!

        String str4 = new String(gbks,"gbk");
        System.out.println(str4);//No garbled code. Reason: the encoding set and decoding set are consistent!
    }
}

1.13 description of String algorithm in interview

1. Simulate a trim method to remove spaces at both ends of the string.

import org.junit.Test;

/*
 * 1.Simulate a trim method to remove spaces at both ends of the string.
 * 
 */
public class StringExer {

	// Question 1
	public String myTrim(String str) {
		if (str != null) {
			int start = 0;// The index used to record the position where the first index position from front to back is not a space
			int end = str.length() - 1;// The index used to record the position where the first index position from back to front is not a space

			while (start < end && str.charAt(start) == ' ') {
				start++;
			}

			while (start < end && str.charAt(end) == ' ') {
				end--;
			}
			if (str.charAt(start) == ' ') {
				return "";
			}

			return str.substring(start, end + 1);
		}
		return null;
	}
	
	@Test
	public void testMyTrim() {
		String str = "   a   ";
		// str = " ";
		String newStr = myTrim(str);
		System.out.println("---" + newStr + "---");
	}
}

2. Inverts a string. Inverts the specified part of the string. For example, "abcdefg" is reversed to "abfedcg"

import org.junit.Test;

public class StringDemo {

    /**
     * Inverts a string. Inverts the specified part of the string. For example, "abcdefg" is reversed to "abfedcg"
     *
     * Method 1: convert to char []
     */
    public String reverse(String str,int startIndex,int endIndex){

        if(str != null && str.length() != 0) {
            char[] arr = str.toCharArray();
            for (int x = startIndex, y = endIndex; x < y; x++, y--) {
                char temp = arr[x];
                arr[x] = arr[y];
                arr[y] = temp;
            }
            return new String(arr);
        }
        return null;
    }

    /**
     * Method 2: use String splicing
     */
    public String reverse2(String str, int startIndex, int endIndex) {
        if(str != null) {
            // Part I
            String reverStr = str.substring(0,startIndex);// ab
            // Part II
            for (int i = endIndex; i >= startIndex; i--) {
                reverStr += str.charAt(i);
            } // abfedc
            // Part III
            reverStr += str.substring(endIndex + 1);

            return reverStr;
        }
        return null;
    }

    //Method 3: replace String with StringBuffer/StringBuilder
    public String reverse3(String str, int startIndex, int endIndex) {
        StringBuilder builder = new StringBuilder(str.length());

        if(str != null) {
            //Part I
            builder.append(str.substring(0, startIndex));

            //Part II
            for (int i = endIndex; i >= startIndex; i--) {

                builder.append(str.charAt(i));
            }
            //Part III
            builder.append(str.substring(endIndex + 1));

            return builder.toString();
        }
        return null;
    }

    @Test
    public void testReverse() {
        String str = "abcdefg";
        String str1 = reverse3(str, 2, 5);
        System.out.println(str1);// abfedcg

    }
}

3. Gets the number of occurrences of one string in another string. For example, get the number of occurrences of "ab" in "abkkcadkabkebfkabkskab"

import org.junit.Test;

public class StringDemo2 {
    /**
     * Gets the number of occurrences of one string in another string.
     * For example, get the number of occurrences of "ab" in "abkkcadkabkebfkabkskab"
     *
     */

    /**
     * Gets the number of occurrences of subStr in mainStr
     * @param mainStr
     * @param subStr
     */
    public int getCount(String mainStr,String subStr){
        int mainLength = mainStr.length();
        int subLength = subStr.length();
        int count = 0;
        int index = 0;

        if(mainLength >= subLength){

            //Mode 1:
//            while((index = mainStr.indexOf(subStr)) != -1){
//                count++;
//                mainStr = mainStr.substring(index + subStr.length());
//            }
            //Mode 2: improvement of mode 1
            while((index = mainStr.indexOf(subStr,index)) != -1){
                count++;
                index += subLength;
            }

            return count;
        }else{
            return 0;
        }
    }

    @Test
    public void testGetCount(){
        String mainStr = "abkkcadkabkebfkabkskab";
        String subStr = "ab";
        int count = getCount(mainStr,subStr);
        System.out.println(count);
    }

}

4. Gets the largest identical substring in two strings. For example:

str1 = "abcwerthelloyuiodef";str2 = "cvhellobnm"

Tip: compare the short string with the substring whose length decreases in turn with the longer string.

import org.junit.Test;

import java.util.Arrays;

public class StringDemo3 {
    /**
     * Gets the largest identical substring in two strings. For example:
     * str1 = "abcwerthelloyuiodef";str2 = "cvhellobnm"
     * Tip: compare the short string with the substring whose length decreases in turn with the longer string.
     */
    //Premise: there is only one largest identical substring in two strings
    public String getMaxSameString(String str1,String str2){
        if(str1 != null && str2 != null){
            String maxStr = (str1.length() >= str2.length())? str1 : str2;
            String minStr = (str1.length() < str2.length())? str1 : str2;
            int length = minStr.length();

            for(int i = 0;i < length;i++){
                for(int x = 0,y = length - i;y <= length;x++,y++){
                    String subStr = minStr.substring(x,y);
                    if(maxStr.contains(subStr)){
                        return subStr;
                    }

                }
            }

        }
        return null;
    }

    // If there are multiple largest substrings of the same length
    // At this point, first return String [], and then replace it with ArrayList in the collection, which is more convenient
    public String[] getMaxSameString1(String str1, String str2) {
        if (str1 != null && str2 != null) {
            StringBuffer sBuffer = new StringBuffer();
            String maxString = (str1.length() > str2.length()) ? str1 : str2;
            String minString = (str1.length() > str2.length()) ? str2 : str1;

            int len = minString.length();
            for (int i = 0; i < len; i++) {
                for (int x = 0, y = len - i; y <= len; x++, y++) {
                    String subString = minString.substring(x, y);
                    if (maxString.contains(subString)) {
                        sBuffer.append(subString + ",");
                    }
                }
//                System.out.println(sBuffer);
                if (sBuffer.length() != 0) {
                    break;
                }
            }
            String[] split = sBuffer.toString().replaceAll(",$", "").split("\\,");
            return split;
        }

        return null;
    }

    @Test
    public void testGetMaxSameString(){
        String str1 = "abcwerthello1yuiodefabcdef";
        String str2 = "cvhello1bnmabcdef";
        String[] maxSameStrings = getMaxSameString1(str1, str2);
        System.out.println(Arrays.toString(maxSameStrings));

    }

}

5. Sort the characters in the string in natural order.

Tips:

1) The string becomes an array of characters.

2) Sort the array, select, bubble, Arrays.sort();

3) Turns the sorted array into a string.

import org.junit.Test;
import java.util.Arrays;

/**
 *
 * 5.Sort the characters in the string in natural order. "abcwerthelloyuiodef"
 * Tips:
 * 		1)The string becomes an array of characters.
 * 		2)Sort the array, select, bubble, Arrays.sort(str.toCharArray());
 * 		3)Turns the sorted array into a string.
 *
 */

public class StringDemo4 {

	// Question 5
	@Test
	public void testSort() {
		String str = "abcwerthelloyuiodef";
		char[] arr = str.toCharArray();
		Arrays.sort(arr);

		String newStr = new String(arr);
		System.out.println(newStr);
	}
}

1.14 introduction to StringBuffer and StringBuilder

/**
 * String,StringBuffer,StringBuilder What are the similarities and differences between the three?
 *
 * String:Immutable character sequence; The bottom layer uses char [] storage
 * StringBuffer:Variable character sequence; Thread safety and low efficiency; The bottom layer uses char [] storage
 * StringBuilder:Variable character sequence; jdk5.0 new, thread unsafe, high efficiency; The bottom layer uses char [] storage
 *
 */

1.15 source code analysis of StringBuffer

import org.junit.Test;

/**
 * About the use of StringBuffer and StringBuilder
 */
public class StringBufferBuilderTest {
    /**
     *
     * Source code analysis:
     * String str = new String();//char[] value = new char[0];
     * String str1 = new String("abc");//char[] value = new char[]{'a','b','c'};
     *
     * StringBuffer sb1 = new StringBuffer();//char[] value = new char[16];The bottom layer creates an array with a length of 16.
     * System.out.println(sb1.length());//
     * sb1.append('a');//value[0] = 'a';
     * sb1.append('b');//value[1] = 'b';
     *
     * StringBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16];
     *
     * //Question 1. System. Out. Println (SB2. Length())// three
     * //Problem 2. Capacity expansion: if the underlying array of data to be added cannot hold enough, the underlying array needs to be expanded.
     *        By default, the capacity is expanded to 2 times + 2 of the original capacity, and the elements in the original array are copied to the new array.
     *
     * Meaning: it is recommended to use StringBuffer(int capacity) or StringBuilder(int capacity) in development
     *
     */
    @Test
    public void test1(){
        StringBuffer sb1 = new StringBuffer("abc");
        sb1.setCharAt(0,'m');
        System.out.println(sb1);

        StringBuffer sb2 = new StringBuffer();
        System.out.println(sb2.length());   //0
    }
}

1.16 common methods in StringBuffer

import org.junit.Test;

/**
 * About the use of StringBuffer and StringBuilder
 */
public class StringBufferBuilderTest {

    /**
     * StringBuffer Common methods of:
     *
     * StringBuffer append(xxx): Many append() methods are provided for string splicing
     * StringBuffer delete(int start,int end): Delete the contents of the specified location
     * StringBuffer replace(int start, int end, String str): Replace the [start,end) position with str
     * StringBuffer insert(int offset, xxx): Insert xxx at the specified location
     * StringBuffer reverse() : Reverses the current character sequence
     * public int indexOf(String str)
     * public String substring(int start,int end):Returns a substring of the left closed right open interval from start to end
     * public int length()
     * public char charAt(int n )
     * public void setCharAt(int n ,char ch)
     *
     * Summary:
     *     Add: append(xxx)
     *     Delete: delete(int start,int end)
     *     Change: setcharat (int n, char CH) / replace (int start, int end, string STR)
     *     Query: charAt(int n)
     *     Insert: insert(int offset, xxx)
     *     Length: length();
     *     Traversal: for() + charAt() / toString()
     *
     */
    @Test
    public void test2(){
        StringBuffer s1 = new StringBuffer("abc");
        s1.append(1);
        s1.append('1');
        System.out.println(s1);
//        s1.delete(2,4);
//        s1.replace(2,4,"hello");
//        s1.insert(2,false);
//        s1.reverse();
        String s2 = s1.substring(1,3);
        System.out.println(s1);
        System.out.println(s1.length());
        System.out.println(s2);
    }
}

1.17 efficiency comparison of String, StringBuffer and StringBuilder

import org.junit.Test;

/**
 * About the use of StringBuffer and StringBuilder
 */
public class StringBufferBuilderTest {

    /**
     * Compare the efficiency of String, StringBuffer and StringBuilder:
     * Arrange from high to low: StringBuilder > StringBuffer > string
     *
     */
    @Test
    public void test3(){
        //Initial settings
        long startTime = 0L;
        long endTime = 0L;
        String text = "";
        StringBuffer buffer = new StringBuffer("");
        StringBuilder builder = new StringBuilder("");
        //Start comparison
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 20000; i++) {
            buffer.append(String.valueOf(i));
        }
        endTime = System.currentTimeMillis();
        System.out.println("StringBuffer Execution time of:" + (endTime - startTime));

        startTime = System.currentTimeMillis();
        for (int i = 0; i < 20000; i++) {
            builder.append(String.valueOf(i));
        }
        endTime = System.currentTimeMillis();
        System.out.println("StringBuilder Execution time of:" + (endTime - startTime));

        startTime = System.currentTimeMillis();
        for (int i = 0; i < 20000; i++) {
            text = text + i;
        }
        endTime = System.currentTimeMillis();
        System.out.println("String Execution time of:" + (endTime - startTime));

    }
}

02. Date time API before JDK 8

2.1. Method for obtaining timestamp in System class

The public static long currentTimeMillis() provided by the System class is used to return the time difference in milliseconds between the current time and 0:0:0 on January 1, 1970.

  • This method is suitable for calculating the time difference.
  • The main criteria for calculating world time are:
    • UTC(Coordinated Universal Time)
    • GMT(Greenwich Mean Time)
    • CST(Central Standard Time)
import org.junit.Test;

/**
 * JDK 8 API test at previous date and time
 */
public class DateTimeTest {

    //1. currentTimeMillis() in system class
    @Test
    public void test1(){
        long time = System.currentTimeMillis();
        //Returns the time difference in milliseconds between the current time and 0:0:0:0 on January 1, 1970.
        //This is called a timestamp
        System.out.println(time);
    }
}

2.2 use of two Date classes in Java

import org.junit.Test;

import java.util.Date;

/**
 * JDK 8 API test at previous date and time
 */
public class DateTimeTest {

    /**
     * java.util.Date Class -- > represents a specific moment, accurate to milliseconds
     *            |---java.sql.Date class
     *
     * 1.Use of two constructors
     *     >Constructor 1: Date(): creates a Date object corresponding to the current time
     *     >Constructor 2: create a Date object with a specified number of milliseconds
     * 2.Use of two methods
     *     >toString():Displays the current year, month, day, hour, minute and second
     *     >getTime():Gets the number of milliseconds corresponding to the current Date object. (timestamp)
     *
     * 3. java.sql.Date A variable that corresponds to the date type in the database
     *     >How to instantiate
     *     >How to convert a java.util.Date object to a java.sql.Date object
     *
     */
    @Test
    public void test2(){
        //Constructor 1: Date(): creates a Date object corresponding to the current time
        Date date1 = new Date();
        System.out.println(date1.toString());   //Sat May 09 20:09:11 CST 2020

        System.out.println(date1.getTime());    //1589026216998

        //Constructor 2: create a Date object with a specified number of milliseconds
        Date date2 = new Date(1589026216998L);
        System.out.println(date2.toString());

        //Create a java.sql.Date object
        java.sql.Date date3 = new java.sql.Date(35235325345L);
        System.out.println(date3);  //1971-02-13

        //How to convert a java.util.Date object to a java.sql.Date object
        //Case 1:
//        Date date4 = new java.sql.Date(2343243242323L);
//        java.sql.Date date5 = (java.sql.Date) date4;
        //Case 2:
        Date date6 = new Date();
        java.sql.Date date7 = new java.sql.Date(date6.getTime());
    }
}

03. Date time API before JDK 8

3.1 use of SimpleDateFormat

  • The API of the Date class is not easy to internationalize, and most of them are abandoned. The java.text.SimpleDateFormat class is a specific class that formats and parses dates in a way that is not related to the language environment.
  • It allows
    • Format: date - > text
    • Parse: text - > date
import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * jdk 8 API test of previous date and time
 * 1.System Class currentTimeMillis();
 * 2.java.util.Date java.sql.Date
 * 3.SimpleDateFormat
 * 4.Calendar
 */
public class DateTime {
    /**
     * SimpleDateFormat Use of: SimpleDateFormat formatting and parsing of Date class
     * 1.Two operations
     * 1.1 Formatting: date -- "string
     * 1.2 Parsing: inverse process of formatting, string -- "date"
     *
     * 2.SimpleDateFormat Instantiation of
     */
    @Test
    public void testSimpleDateFormat() throws ParseException {
        //Instantiate SimpleDateFormat
        SimpleDateFormat sdf = new SimpleDateFormat();

        //Formatting: date -- "string
        Date date = new Date();
        System.out.println(date);   //Sun May 10 16:34:30 CST 2020

        String format = sdf.format(date);
        System.out.println(format); //20-5-10 4:34 PM

        //Parsing: inverse process of formatting, string -- "date"
        String str = "19-12-18 11 a.m:43";
        Date date1 = sdf.parse(str);
        System.out.println(date1);  //Wed Dec 18 11:43:00 CST 2019

        //*************Format and parse as specified: call the constructor with parameters*****************
//        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
        //format
        String format1 = sdf1.format(date);
        System.out.println(format1);    //02020. May. 10 A.D. 04:32 PM
        //Parsing: the string must conform to the format recognized by SimpleDateFormat (reflected by constructor parameters),
        //Otherwise, throw the exception
        Date date2 = sdf1.parse("02020.May.10 04 A.D:32 afternoon");
        System.out.println(date2);  //Sun May 10 16:32:00 CST 2020
    }
}

3.2 practice of SimpleDateFormat

1. Exercise 1

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * jdk 8 API test of previous date and time
 * 1.System Class currentTimeMillis();
 * 2.java.util.Date java.sql.Date
 * 3.SimpleDateFormat
 * 4.Calendar
 */
public class DateTime {

    /**
     * Exercise 1: convert the string "2020-09-08" to java.sql.Date
     *
     */
    @Test
    public void testExer() throws ParseException {
        String birth = "2020-09-08";

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf1.parse(birth);
//        System.out.println(date);

        java.sql.Date birthDate = new java.sql.Date(date.getTime());
        System.out.println(birthDate);
    }
}

2. Exercise 2

    /**
     * Exercise 2: "fishing in three days and drying nets in two days" 1990-01-01 XXXX XX fishing? Drying the net?
     *
     *     For example: September 8, 2020? Total days
     *
     *     Total days% 5 = = 1,2,3: Fishing
     *     Total days% 5 = = 4,0: net drying
     *
     *     Calculation of total days?
     *     Method 1: (date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24) + 1
     *     Method 2: January 1, 1990 -- > December 31, 2019 + January 1, 2020 -- > September 8, 2020
     *
     */

3.3. Use of Calendar

  • Calendar is an abstract base class, which is mainly used to complete the mutual operation between date fields.
  • Method to get Calendar instance
    • Use the Calendar.getInstance() method
    • Call the constructor of its subclass GregorianCalendar.
  • An example of Calendar is the abstract representation of system time. The desired time information is obtained through the get(intfield) method. For example, YEAR, MONTH, DAY_OF_WEEK,HOUR_OF_DAY ,MINUTE,SECOND
    • public void set(intfield,intvalue)
    • public void add(intfield,intamount)
    • public final Date getTime()
    • public final void setTime(Date date)
  • be careful:
    • When getting the month: January is 0, February is 1, and so on, December is 11
    • Get week time: Sunday is 1, Tuesday is 2,.... Saturday is 7
import java.util.Calendar;
import java.util.Date;

import org.junit.Test;

/**
 * jdk 8 API test of previous date and time
 * 1.System Class currentTimeMillis();
 * 2.java.util.Date java.sql.Date
 * 3.SimpleDateFormat
 * 4.Calendar
 */
public class DateTime {

    /**
     * Calendar Use of Calendar Class
     */
    @Test
    public void testCalendar(){
        //1. Instantiation
        //Method 1: create an object of its subclass (Gregorian calendar)
        //Method 2: call its static method getInstance()
        Calendar calendar = Calendar.getInstance();

//        System.out.println(calendar.getClass());    //class java.util.GregorianCalendar

        //2. Common methods
        //get()
        int days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);   //10
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //131. Today is 131 days of the year

        //set()
        //calendar variability
        calendar.set(Calendar.DAY_OF_MONTH,22);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);   //22

        //add()
        calendar.add(Calendar.DAY_OF_MONTH,-3);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);   //22-3 -->19

        //getTime(): Calendar Class -- > date
        Date date = calendar.getTime();
        System.out.println(date);   //Tue May 19 17:12:06 CST 2020

        //Settime(): date -- > Calendar Class
        Date date1 = new Date();
        calendar.setTime(date1);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);   //10
    }
}

04. Introduction to date time API in JDK8

1. Background of the new datetime API

If we can say to others, "let's meet at 1502643933071, don't be late!" then it would be very simple. But we want time to be related to day and night and the four seasons, so things get complicated. JDK 1.0 includes a java.util.Date class, but most of its methods have been deprecated after JDK 1.1 introduced the calendar class. Calendar is not much better than date. The problems they face are:

  • Variability: classes like date and time should be immutable.
  • Offset: the year in Date starts from 1900, and the month starts from 0.
  • Formatting: formatting is only useful for Date, but not Calendar.
  • In addition, they are not thread safe; Cannot handle leap seconds, etc.
import org.junit.Test;
import java.util.Date;

/**
 * jdk 8 Testing of date time API in
 *
 */
public class JDK8DateTimeTest {

    @Test
    public void testDate(){
        //Offset
        Date date1 = new Date(2020,9,8);
        System.out.println(date1);  //Fri Oct 08 00:00:00 CST 3920

        Date date2 = new Date(2020 - 1900,9 - 1,8);
        System.out.println(date2); //Tue Sep 08 00:00:00 CST 2020
    }
}

The API introduced for the third time is successful, and the java.time API introduced in Java 8 has corrected the defects in the past, and it will serve us for a long time in the future.

Java 8 absorbs the essence of Joda-Time and creates a good API for Java with a new start. The new java.time contains all classes about local Date, local time, local datetime, ZonedDateTime, and Duration. The long-standing Date class adds a toinst () method to convert Date into a new representation. These new localized time and Date APIs greatly simplify the management of Date and time and localization.

java.time–Base package containing value objects
java.time.chrono–Provides access to different calendar systems java.time.format–Format and parse time and date java.time.temporal–Including the underlying framework and extension features java.time.zone–Contains time zone supported classes

Note: most developers only use basic packages and format Package, may also be used temporal Bag. Therefore, although there are 68 new public types, most developers will use only about one-third of them.

4.1. Use of LocalDate, LocalTime and LocalDateTime

  • LocalDate, LocalTime and LocalDateTime are the more important classes. Their instances are immutable objects that represent the date, time, date and time using the ISO-8601 calendar system. They provide a simple local date or time and do not contain current time information or time zone related information.
    • LocalDate represents the date in IOS format (yyyy MM DD). It can store birthday, anniversary and other dates.
    • LocalTime represents a time, not a date.
    • LocalDateTime is used to represent date and time, which is one of the most commonly used classes.
  • Note: ISO-8601 calendar system is the representation of the date and time of modern citizens formulated by the international organization for standardization, that is, the Gregorian calendar.
import org.junit.Test;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * jdk 8 Testing of date time API in
 */
public class JDK8DateTimeTest {

    /**
     * LocalDate,LocalTime,LocalDateTime Use of
     *
     */
    @Test
    public void test1(){
        //now(): get the current date, time, date + time
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();

        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

        //of(): set the specified year, month, day, hour, minute and second. No offset
        LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
        System.out.println(localDateTime1);

        //getXxx(): get related properties
        System.out.println(localDateTime.getDayOfMonth());
        System.out.println(localDateTime.getDayOfWeek());
        System.out.println(localDateTime.getMonth());
        System.out.println(localDateTime.getMonthValue());
        System.out.println(localDateTime.getMinute());

        //Reflect immutability
        //withXxx(): set related properties
        LocalDate localDate1 = localDate.withDayOfMonth(22);
        System.out.println(localDate);
        System.out.println(localDate1);

        LocalDateTime localDateTime2 = localDateTime.withHour(4);
        System.out.println(localDateTime);
        System.out.println(localDateTime2);

        //Immutability
        LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
        System.out.println(localDateTime);
        System.out.println(localDateTime3);

        LocalDateTime localDateTime4 = localDateTime.minusDays(6);
        System.out.println(localDateTime);
        System.out.println(localDateTime4);
    }
}

4.2. Use of Instant class

  • Instant: an instantaneous point on the timeline. This may be used to record event timestamps in the application.
  • When dealing with time and date, we usually think of year, month, day, hour, minute and second. However, this is only a model of time, which is human oriented. The second general model is machine oriented, or continuous. In this model, a point in the timeline is represented as a large number, which is conducive to computer processing. In UNIX, this number has been in seconds since 1970; Similarly, in Java, it began in 1970, but in milliseconds.
  • The java.time package provides the machine view through the value type instant T, and does not provide the time unit in the human sense. Instant represents a point on the timeline without any contextual information, such as time zone. Conceptually, it simply represents the number of seconds since 0:0:0 (UTC) on January 1, 1970. Because the java.time package is based on Nanosecond calculation, the accuracy of instant can reach nanosecond level.

(1 ns = 10-9s) 1 second = 1000 milliseconds = 106 microseconds = 109 nanoseconds

Timestamp refers to the total number of seconds from 00:00:00 GMT on January 1, 1970 (08:00:00 GMT on January 1, 1970) to the present.

import org.junit.Test;

import java.time.*;

/**
 * jdk 8 Testing of date time API in
 */
public class JDK8DateTimeTest {

    /**
     * Instant Use of
     */
    @Test
    public void test2(){
        //now(): get the standard time corresponding to the original meridian
        Instant instant = Instant.now();
        System.out.println(instant);    //2020-05-10T09:55:55.561Z

        //Add offset of time
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));//Dongba District
        System.out.println(offsetDateTime); //2020-05-10T18:00:00.641+08:00

        //Toepochmili(): get the number of milliseconds since 0:0:0 (UTC) on January 1, 1970 -- > getTime() of date class
        long milli = instant.toEpochMilli();
        System.out.println(milli);  //1589104867591

        //Ofepochmili(): get the Instant instance -- > date (long millisecond) by the given number of milliseconds
        Instant instant1 = Instant.ofEpochMilli(1550475314878L);
        System.out.println(instant1);   //2019-02-18T07:35:14.878Z
    }
}

4.3 use of DateTimeFormatter

java.time.format.DateTimeFormatter class: this class provides three formatting methods:

  • Predefined standard formats. For example: * * ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME **
  • Localization related formats. For example: oflocalized datetime (formatstyle. Long)
  • **Custom format. For example: ofPattern("yyyy MM DD HH: mm: SS")**
import org.junit.Test;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;

/**
 * jdk 8 Testing of date time API in
 */
public class JDK8DateTimeTest {

    /**
     * DateTimeFormatter:Format or parse date and time
     *     Similar to SimpleDateFormat
     */
    @Test
    public void test3(){
        //Method 1: predefined standard format. E.g. ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //Format: date -- > string
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);
        System.out.println(str1);//2020-05-10T18:26:40.234

        //Parsing: String -- > date
        TemporalAccessor parse = formatter.parse("2020-05-10T18:26:40.234");
        System.out.println(parse);

        //Mode 2:
        //Localization related formats. For example: ofLocalizedDateTime()
        //Formatstyle.long/formatstyle.medium/formatstyle.short: applicable to LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        //format
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//May 10, 2020 06:26:40 PM

        //Localization related formats. For example: ofLocalizedDate()
        //Formatstyle.full/formatstyle.long/formatstyle.medium/formatstyle.short: applicable to LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
        //format
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);//2020-5-10


       //Key point: Method 3: custom format. For example: ofPattern("yyyy MM DD HH: mm: SS")
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //format
        String str4 = formatter3.format(LocalDateTime.now());
        System.out.println(str4);//2020-05-10 06:26:40

        //analysis
        TemporalAccessor accessor = formatter3.parse("2020-05-10 06:26:40");
        System.out.println(accessor);

    }
}

4.4 use of other date and time related API s

  • ZoneId: this class contains all time zone information, including the ID of a time zone, such as Europe/Paris
  • ZonedDateTime: a date and time in the time zone of the ISO-8601 calendar system, such as 2007-12-03t10:15:30 + 01:00 Europe / Paris.
    • Each time zone corresponds to an ID, and the region ID is in the format of "{region} / {City}", such as Asia/Shanghai, etc
import org.junit.Test;

import java.time.*;
import java.util.Set;

/**
 * jdk 8 Testing of date time API in
 */
public class JDK8DateTimeTest {
	
	@Test
	public void test1(){
		//ZoneId: class contains all time zone information
		// getAvailableZoneIds() of ZoneId: get all ZoneId
		Set<String> zoneIds= ZoneId.getAvailableZoneIds();
		for(String s: zoneIds) {
			System.out.println(s);
		}
		// of() of ZoneId: gets the time of the specified time zone
		LocalDateTime localDateTime= LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
		System.out.println(localDateTime);
		
		//ZonedDateTime: date time with time zone
		// now() of ZonedDateTime: get the ZonedDateTime object of the current time zone
		ZonedDateTime zonedDateTime= ZonedDateTime.now();
		System.out.println(zonedDateTime);
		// ZonedDateTime now (zoneid): gets the ZonedDateTime object of the specified time zone
		ZonedDateTime zonedDateTime1= ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
		System.out.println(zonedDateTime1);
	}
}

  • Clock: a clock that uses a time zone to provide access to the current instant, date, and time.
  • Duration: duration, used to calculate two "time" intervals
  • Date interval: Period, used to calculate two "date" intervals
  • TemporalAdjuster: time corrector. Sometimes we may need to obtain, for example, adjust the date to "next working day".
  • TemporalAdjusters: this class provides a large number of common TemporalAdjusters through static methods (firstDayOfXxx()/lastDayOfXxx()/nextXxx()).
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;

import org.junit.Test;

public class JDK8APITest {
	
	@Test
	public void test2(){
		//Duration: used to calculate two "time" intervals, based on seconds and nanoseconds
		LocalTime localTime= LocalTime.now();
		LocalTime localTime1= LocalTime.of(15, 23, 32);
		//between(): a static method that returns a Duration object that represents the interval between two times
		Duration duration= Duration.between(localTime1, localTime);
		System.out.println(duration);
		
		System.out.println(duration.getSeconds());
		System.out.println(duration.getNano());
		
		LocalDateTime localDateTime= LocalDateTime.of(2016, 6, 12, 15, 23, 32);
		LocalDateTime localDateTime1= LocalDateTime.of(2017, 6, 12, 15, 23, 32);
		
		Duration duration1= Duration.between(localDateTime1, localDateTime);
		System.out.println(duration1.toDays());
	}
}

import java.time.Period;
import org.junit.Test;

public class JDK8APITest {
	
	@Test
	public void test3(){
		//Period: used to calculate the interval between two dates, measured by year, month and day
		LocalDate localDate= LocalDate.now();
		LocalDate localDate1= LocalDate.of(2028, 3, 18);
		
		Period period= Period.between(localDate, localDate1);
		System.out.println(period);
        System.out.println(period.getYears());
		
		System.out.println(period.getMonths());
		System.out.println(period.getDays());
		
		Period period1= period.withYears(2);
		System.out.println(period1);
	}
}

4.4.1 reference: conversion from traditional date processing

05. Java comparator

5.1 overview

Under normal circumstances, objects in Java can only be compared: = = or! =. You can't use > or < but in the development scenario, we need to sort mu lt iple objects. By implication, we need to compare the size of objects. How? Use either of the two interfaces: Comparable or Comparator

  • There are two ways to sort objects in Java:
    • Natural sorting: java.lang.Comparable
    • Custom sorting: java.util.Comparator

5.2 examples of Comparable natural sorting

import org.junit.Test;
import java.util.Arrays;

public class CompareTest {

    /**
     * Comparable Interface example: natural sorting
     * 1.For example, String and wrapper classes implement the Comparable interface, rewrite the compareTo(obj) method, and give a way to compare the sizes of two objects.
     * 2.For example, String and wrapper classes are arranged from small to large after rewriting the compareTo() method
     * 3. Rules for rewriting compareTo(obj):
     *    If the current object this is greater than the formal parameter object obj, a positive integer is returned,
     *    If the current object this is less than the formal parameter object obj, a negative integer is returned,
     *    Returns zero if the current object this is equal to the parameter object obj.
     *
     */
    @Test
    public void test1(){
        String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"};

        Arrays.sort(arr);

        System.out.println(Arrays.toString(arr));
    }

}

5.3. The user-defined class implements Comparable natural sorting

1. Test class

import org.junit.Test;
import java.util.Arrays;

public class CompareTest {

    /**
     * 4.For custom classes, if sorting is required, we can let the custom class implement the Comparable interface and override the compareTo(obj) method.
     *   Indicate how to sort in the compareTo(obj) method
     */
    @Test
    public void test2(){
        Goods[] arr = new Goods[5];
        arr[0] = new Goods("lenovoMouse",34);
        arr[1] = new Goods("dellMouse",43);
        arr[2] = new Goods("xiaomiMouse",12);
        arr[3] = new Goods("huaweiMouse",65);
        arr[4] = new Goods("microsoftMouse",43);

        Arrays.sort(arr);

        System.out.println(Arrays.toString(arr));
    }

}

2. Goods class

/**
 * Commodity category
 */
public class Goods implements Comparable{

    private String name;
    private double price;

    public Goods() {
    }

    public Goods(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    //Specify the way to compare the size of goods: sort according to the price from low to high, and then sort according to the product name from high to low
    @Override
    public int compareTo(Object o) {
//        System.out.println("**************");
        if(o instanceof Goods){
            Goods goods = (Goods)o;
            //Mode 1:
            if(this.price > goods.price){
                return 1;
            }else if(this.price < goods.price){
                return -1;
            }else{
//                return 0;
                return -this.name.compareTo(goods.name);
            }
            //Mode 2:
//           return Double.compare(this.price,goods.price);
        }
//        return 0;
        throw new RuntimeException("The data type passed in is inconsistent!");
    }
}

5.4. Using Comparator to realize customized sorting

import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;

/**
 * 1, Note: under normal circumstances, objects in Java can only be compared: = = or! =. Cannot use > or <
 *          However, in the development scenario, we need to sort multiple objects. By implication, we need to compare the size of objects.
 *          How? Use either of the two interfaces: Comparable or Comparator
 *
 * 2, Comparison between Comparable interface and Comparator:
 *    Comparable Once the interface mode is fixed, ensure that the object of the implementation class of the Comparable interface can be compared in size at any position.
 *    Comparator The interface is a temporary comparison.
 */
public class CompareTest {

    /**
     * Comparator Interface usage: custom sorting
     *     1.Background:
     *     When the element type does not implement the java.lang.Comparable interface and it is inconvenient to modify the code,
     *     Or the sorting rules that implement the java.lang.Comparable interface are not suitable for the current operation,
     *     Then consider using Comparator objects to sort
     *     2.Rewrite the compare(Object o1,Object o2) method to compare the sizes of o1 and o2:
     *     If the method returns a positive integer, o1 is greater than o2;
     *     If 0 is returned, it means equal;
     *     Returns a negative integer indicating that o1 is less than o2.
     */
    @Test
    public void test3(){
        String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"};
        Arrays.sort(arr,new Comparator(){

            //Arrange strings in descending order
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof String && o2 instanceof  String){
                    String s1 = (String) o1;
                    String s2 = (String) o2;
                    return -s1.compareTo(s2);
                }
//                return 0;
                throw new RuntimeException("The data type entered is inconsistent");
            }
        });
        System.out.println(Arrays.toString(arr));
    }

    @Test
    public void test4(){
        Goods[] arr = new Goods[6];
        arr[0] = new Goods("lenovoMouse",34);
        arr[1] = new Goods("dellMouse",43);
        arr[2] = new Goods("xiaomiMouse",12);
        arr[3] = new Goods("huaweiMouse",65);
        arr[4] = new Goods("huaweiMouse",224);
        arr[5] = new Goods("microsoftMouse",43);

        Arrays.sort(arr, new Comparator() {
            //Specify the way to compare the size of goods: sort according to the product name from low to high, and then sort according to the price from high to low
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Goods && o2 instanceof Goods){
                    Goods g1 = (Goods)o1;
                    Goods g2 = (Goods)o2;
                    if(g1.getName().equals(g2.getName())){
                        return -Double.compare(g1.getPrice(),g2.getPrice());
                    }else{
                        return g1.getName().compareTo(g2.getName());
                    }
                }
                throw new RuntimeException("The data type entered is inconsistent");
            }
        });

        System.out.println(Arrays.toString(arr));
    }

Comparison between Comparable interface and Comparator:

  • Once the method of the Comparable interface is fixed, it can ensure that the objects of the implementation class of the Comparable interface can be compared in size at any position.
  • The Comparator interface is a temporary comparison.

06. System class, Math class, BigInteger and BigDecimal

6.1 System class

  • The System class represents the System. Many System level properties and control methods are placed inside this class. This class is located in the java.lang package.

  • Because the constructor of this class is private, the object of this class cannot be created, that is, the class cannot be instantiated. Its internal member variables and member methods are static, so they can also be called conveniently.

  • Member variable

    • The System class contains three member variables: in, out and err, which represent standard input stream (keyboard input), standard output stream (display) and standard error output stream (display) respectively.
  • Member method

    • native long currentTimeMillis() :

      The function of this method is to return the current computer time. The expression format of time is the millisecond difference between the current computer time and GMT (Greenwich mean time) on January 1, 1970.

    • void exit(int status) :

      The function of this method is to exit the program. The value of status is 0, which represents normal exit, and non-zero represents abnormal exit. Using this method, the exit function of the program can be realized in the graphical interface programming.

    • void gc() :

      The function of this method is to request the system for garbage collection. Whether the system recycles immediately depends on the implementation of the garbage collection algorithm in the system and the execution of the system. String

    • getProperty(String key) :

      This method is used to obtain the value corresponding to the attribute named key in the system. The common attribute names and functions in the system are shown in the following table:

import org.junit.Test;

/**
 * Use of other common classes
 * 1.System
 * 2.Math
 * 3.BigInteger BigDecimal
 */
public class OtherClassTest {

    @Test
    public void test1() {
        String javaVersion = System.getProperty("java.version");
        System.out.println("java of version:" + javaVersion);

        String javaHome = System.getProperty("java.home");
        System.out.println("java of home:" + javaHome);

        String osName = System.getProperty("os.name");
        System.out.println("os of name:" + osName);

        String osVersion = System.getProperty("os.version");
        System.out.println("os of version:" + osVersion);

        String userName = System.getProperty("user.name");
        System.out.println("user of name:" + userName);

        String userHome = System.getProperty("user.home");
        System.out.println("user of home:" + userHome);

        String userDir = System.getProperty("user.dir");
        System.out.println("user of dir:" + userDir);

    }
}

6.2 Math class

java.lang.Math provides a series of static methods for scientific computing. The parameter and return value types of the method are generally double.

  • abs absolute value
  • acos,asin,atan,cos,sin,tan trigonometric function
  • Square root of sqrt
  • Pow (double a, double b) a to the power of b
  • log natural logarithm
  • exp e is the bottom index
  • max(double a,double b)
  • min(double a,double b)
  • random() returns a random number from 0.0 to 1.0
  • Long round (double a) data a of double type is converted to long type (rounded)
  • Todegrees (double angle) radians - > angle
  • toRadians(double angdeg) angle - > radians

6.3 BigInteger and BigDecimal

  • As the wrapper class of int, the Integer class can store the maximum Integer value of 2 ^ 31 - 1, and the Long class is also limited, with the maximum value of 2 ^ 63 - 1. If you want to represent a large Integer, neither the basic data type nor their wrapper class can do anything, let alone operate.
  • The BigInteger of the java.math package can represent immutable integers of arbitrary precision. BigInteger provides the counterparts of all Java's basic integer operators and all related methods of java.lang.Math. In addition, BigInteger also provides the following operations: modular arithmetic, GCD calculation, prime test, prime generation, bit operation, and some other operations.
  • constructor
    • BigInteger(String val): build BigInteger objects based on strings
  • common method
  • The general Float class and Double class can be used for scientific calculation or engineering calculation, but in commercial calculation, the digital accuracy is required, so the java.math.BigDecimal class is used.
  • The BigDecimal class supports immutable signed decimal points of arbitrary precision.
  • constructor
    • public BigDecimal(double val)
    • public BigDecimal(String val)
  • common method
    • public BigDecimal add(BigDecimal augend)
    • public BigDecimal subtract(BigDecimal subtrahend)
    • public BigDecimal multiply(BigDecimal multiplicand)
    • public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
import org.junit.Test;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * Use of other common classes
 * 1.System
 * 2.Math
 * 3.BigInteger BigDecimal
 */
public class OtherClassTest {

    @Test
    public void test2() {
        BigInteger bi = new BigInteger("1243324112234324324325235245346567657653");
        BigDecimal bd = new BigDecimal("12435.351");
        BigDecimal bd2 = new BigDecimal("11");
        System.out.println(bi);
//         System.out.println(bd.divide(bd2));
        System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));
        System.out.println(bd.divide(bd2, 25, BigDecimal.ROUND_HALF_UP));

    }
}

Tags: Java

Posted on Wed, 06 Oct 2021 18:18:34 -0400 by ubersmuck