Java notes 11 common classes

Posted by $kevan on Mon, 07 Mar 2022 20:43:07 +0100

11.1 packaging

11.1.1 classification of packaging

For the eight basic types, the corresponding reference type -- wrapper class

With the characteristics of the class, you can call the methods in the class

Basic data typePackaging
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble

11.1.2 conversion of packaging and basic data

  1. jdk5 was packed and unpacked manually

    1. Manual packing:

      1. Packing type packing type object = new packing type (basic type variable);

      2. Or: packing type packing type object = packing type Valueof (basic type variable);

      3. int n1 = 100;
        Integer integer = new Integer(n1);
        Integer integer1 = Integer.valueOf(n1);
        
    2. Manual unpacking:

      1. Basic type basic type variable name = wrapper type object xxxValue();
      2. For example: int i = integer intValue();
  2. jdk5 and later adopt automatic packing and unpacking (direct use =)

    1. Automatic packing:
      1. Integer integer2 = n2; // The bottom layer uses integer valueOf(n2)
    2. Automatic unpacking:
      1. int n3 = integer2; // The bottom layer still uses the intValue() method

11.1.3 practice

Are the output results of the following two sections of code the same?

  1. Object obj1 = true ? new Integer(1) : new Double(2.0);
    System.out.println(obj1);	//1.0
    //Ternary operators are a whole, with Integer at the front and Double at the back
    //Double has higher precision and automatic type promotion
    
  2. Object obj2;
    if (true) {
        obj2 = new Integer(1);
    } else {
        obj2 = new Double(2.0);
    }
    System.out.println(obj2);	//1
    

11.1.4 conversion between package type and String type

Take Integer as an example:

public class WrapperString {
    public static void main(String[] args) {
        //Wrapper class (Integer) = String
        Integer i = 100;    //Automatic packing
        //Mode 1
        String str1 = i + "";
        //Mode 2
        String str2 = i.toString();
        //Mode 3
        String str3 = String.valueOf(i);

        //String = wrapper class (Integer)
        String str4 = "12345";
        //Mode 1
        Integer i2 = Integer.parseInt(str4);    //parseInt() returns int, which is then automatically boxed
        //Mode 2
        Integer i3 = new Integer(str4); //Constructor, essentially calling parseInt()
    }
}

11.1.5 common methods of integer class and Character class

public class WrapperMethod {
    public static void main(String[] args) {
        //Integer
        System.out.println(Integer.MIN_VALUE);//Returns the minimum value
        System.out.println(Integer.MAX_VALUE);//Returns the maximum value

        //Character
        System.out.println(Character.isDigit('a'));//Judge whether it is a number
        System.out.println(Character.isLetter('a'));//Judge whether it is a letter
        System.out.println(Character.isUpperCase('a'));//Judge whether it is capitalized
        System.out.println(Character.isLowerCase('a'));//Judge whether it is lowercase
        System.out.println(Character.isWhitespace('a'));//Judge whether it is a space
        System.out.println(Character.toUpperCase('a'));//Convert to uppercase
        System.out.println(Character.toLowerCase('a'));//Convert to lowercase
    }
}

11.1.6 Integer interview questions

//The output result is?
public class IntegerExer {
    public static void main(String[] args) {
        Integer i = new Integer(1);
        Integer j = new Integer(1);
        System.out.println(i == j);

        Integer m = 1;
        Integer n = 1;
        System.out.println(m == n);

        Integer x = 128;
        Integer y = 128;
        System.out.println(x == y);
        
        Integer a = 127;
        int b = 127;
        System.out.println(a == b);
    }
}
  1. i and j are different Integer objects from new, and the comparison result through = is false

  2. m and n adopt automatic packing. The bottom layer is to call the valueOf() method to check the source code

    1. public static Integer valueOf(int i) {
              if (i >= IntegerCache.low && i <= IntegerCache.high)
                  return IntegerCache.cache[i + (-IntegerCache.low)];
              return new Integer(i);
          }
      //IntegerCache.low = -128
      //IntegerCache.high = 127
      
    2. It can be seen that when the range is - 128 ~ 127, an Integer object is returned directly without new, so m and n point to the same object, so = the result of comparison is true

  3. Because x and y are out of the range of - 128 ~ 127, they point to two new Integer objects. Therefore, the result of = comparison is false

  4. a and b are compared. Since b is the basic data type and determines whether the values are equal, it outputs true

11.2 String class

11.2.1 introduction

  1. The String object is used to save a String, that is, a String of character sequences
  2. A string constant object is a sequence of characters enclosed in double quotes. For example: "hello", "12.97", "boy", etc
  3. The characters of the string are encoded in Unicode. One character (whether letter or Chinese character) occupies two bytes
  4. Common constructors of String class:
    1. String s1 = new String();
    2. String s2 = new String(String original);
    3. String s3 = new String(char[] a);
    4. String s1 = new String(char[] a, int startIndex, int count);

Serialization can be transmitted over the network

11.2.2 two methods of creating String objects

  1. Directly assign String s = "hello";
    1. First, check whether there is a "hello" data space from the constant pool. If so, point to it directly; If not, recreate and point to. s finally points to the spatial address of the constant pool
  2. Call constructor String s2 = new String("hello");
    1. First, create a space in the heap, which maintains the value attribute and points to the Hello space in the constant pool. If there is no "hello" in the constant pool, recreate it. If there is, point to it directly through value. s2 finally points to the spatial address in the heap
    2. value is of final type. The address pointed to cannot be changed, but the content stored in its address can be changed

11.2.3 practice

  1. String a = "abc";	//"abc" is not found in the constant pool, otherwise it will be created
    String b = "abc";	//Find "abc" in the constant pool. The previous statement must have been executed, so it points to the same as a
    System.out.println(a.equals(b));	//true
    System.out.println(a == b);			//true
    
  2. String a = new String("abc");
    String b = new String("abc");
    System.out.println(a.equals(b));	//true
    System.out.println(a == b);			//false, a and b are addresses pointing to value, which are different. Two values point to the same "abc" in the constant pool
    
  3. String a = "abc";
    String b = new String("abc");
    System.out.println(a.equals(b));	//true
    System.out.println(a == b);			//false
    System.out.println(a == b.intern());	//true
    System.out.println(b == b.intern());	//false
    //When calling the intern() method, if the pool already contains a String equal to this String object
    //(determined by the equals(Object) method), the string in the pool is returned
    //Otherwise, add a String object to the pool and return a reference to the String object
    //The intern() method finally returns the address of the constant pool
    

11.2.4 characteristics of string

  1. String is a final class that represents an immutable character sequence
  2. String is immutable. Once a string object is allocated, its content is immutable

11.2.5 interview questions

  1. //The following code creates several objects
    String s1 = "hello";
    s1 = "haha";
    //Two objects were created
    

  1. //The following code creates several objects
    String a = "hello" + "abc";
    //When an object is created, the compiler will optimize it to String a = "helloabc"
    
  2. //The following code creates several objects
    String a = "hello";
    String b = "abc";
    String c = a + b;
    //There are three String objects
    //String c = a + b the underlying logic is:
    //StringBuilder sb = new StringBuilder();
    //sb.append(a); sb.append(b); Append the values of a and B to sb
    //String c = sb.toString();  Convert sb into a string object and return it to C
    //toString() uses new, so c points to the heap
    //String a = "hello" + "abc"; Constant addition, looking at the pool
    //String c = a + b; The addition of variables is in the heap
    

  3. String s1 = "hello";
    String s2 = "abc";
    String s3 = "helloabc";
    String s4 = (S1 + S2).intern();
    System.out.println(s3 == s4);	//true
    System.out.println(s3.equals(s4));	//true
    
  4. //!!! Output what?
    public class StringExer {
        String str = new String("hsp");
        final char[] ch = {'j','a','v','a'};
        public void change(String str, char ch[]) {
            str = "java";
            ch[0] = 'h';
        }
    
        public static void main(String[] args) {
            StringExer stringExer = new StringExer();
            stringExer.change(stringExer.str,stringExer.ch);
            System.out.print(stringExer.str + " ");//hsp
            System.out.println(stringExer.ch);	//hava
        }
    }
    

    11.2.6 common methods of string class

    11.2.6.1 description

    String class is used to save string constants. It needs to reopen space every time it is updated, which is inefficient. Therefore, Java designers also provide StringBuilder and StringBuffer to enhance the function of string and improve efficiency

    11.2.6.2 common methods

    • equals: case sensitive to determine whether the contents are equal

    • equalsIgnoreCase: ignore case and judge whether the contents are equal

    • Length: gets the number of characters and the length of the string

    • indexOf: gets the index of the first occurrence of the character in the string. If it cannot be found, it returns - 1

    • lastIndexOf: gets the index of the last occurrence of the character in the string. The index starts from zero and returns - 1 if it cannot be found

    • subString: intercept the subString in the specified range, startIndex~endIndex-1

      • String name = "hello,Zhang San";
        System.out.println(name.substring(6));//Intercept the characters after index 6
        
      • System.out.println(name.substring(2,5));//llo
        
    • Before and after: trim

    • charAt: get the characters at an index. Note that Str[index] cannot be used

    • toUpperCase: convert to uppercase

    • toLowerCase: convert to lowercase

    • connat: concatenate strings

    • replace: replaces characters in a string

      • s1. The result returned after the replace () method is executed is the replaced result, S1 unchanged
    • Split: split string. For some split strings, we need to escape the character \, such as "| \"

      • Sreing road = "E:\\aaa\\bbb";
        String split = road.split("\\\\");
        
    • compareTo: compares the size of two strings

      • public int compareTo(String anotherString) {
                int len1 = value.length;
                int len2 = anotherString.value.length;
                int lim = Math.min(len1, len2);
                char v1[] = value;
                char v2[] = anotherString.value;
        
                int k = 0;
                while (k < lim) {
                    char c1 = v1[k];
                    char c2 = v2[k];
                    if (c1 != c2) {
                        return c1 - c2;
                    }
                    k++;
                }
                return len1 - len2;
            }
        

        The comparison starts from the first character. If they are different, the Unicode value difference is returned. If they are the same, the length difference is returned

    • toCharArray: convert to string array

    • Format: format string

      • Placeholder:% s string,% c character,% d integer,%. 2f floating point

      • %. 2f means to replace with decimal. After replacement, only two decimal places will be reserved and rounded

      • String name = "john";
        int age = 10;
        double score = 56.857;
        char gender = 'male';
        String formatStr = "My name is%s Age is%d,The result is%.2f Gender is%c.I hope you like me!";
        String info2 = String.format(formatStr, name, age, score, gender);
        System.out.println(info2);
        //My name is john, my age is 10, my grade is 56.86, and my gender is male I hope you like me!
        

11.3 StringBuffer class

11.3.1 introduction

  • StringBuffer represents a variable character sequence. You can add or delete string contents

  • Many methods are the same as String, but StringBuffer is of variable length

  • StringBuffer is a container

public final class StringBuffer
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
  1. The immediate parent of StringBuffer is AbstractStringBuilder
  2. StringBuffer implements Serializable, that is, the objects of StringBuffer can be serialized
  3. In the parent class, AbstractStringBuilder has the attribute char[] value, which is not final. The value array stores the string content and leads to the value stored in the heap
  4. StringBuffer is a final class and cannot be inherited
  5. Because the character content of StringBuffer has char[] value, all of which are changing (adding / deleting), and there is no need to change the address every time (that is, not creating a new object every time), the efficiency is higher than that of String

11.3.2 difference from String

  1. String saves character constants, and the value inside cannot be changed. Each update of string class actually changes the address, which is inefficient
  2. StringBuffer saves string variables. The value inside can be changed. Each update of StringBuffer can actually update the content without updating the address every time, which is more efficient

11.3.3 conversion between string and StringBuffer

public class StringAndStringBuffer {
    public static void main(String[] args) {
        //String —> StringBuffer
        String str = "hello tom";
        //Mode 1 use constructor
        //Note: the returned object is the StringBuffer object, which has no effect on str itself
        StringBuffer stringBuffer = new StringBuffer(str);
        //Method 2 uses the append method
        StringBuffer stringBuffer1 = new StringBuffer();
        stringBuffer1 = stringBuffer1.append(str);
        
        //StringBuffer -> String
        StringBuffer stringBuffer3 = new StringBuffer("Han Shunping Education");
        //Method 1: use the toString method provided by StringBuffer
        String s = stringBuffer3.toString();
        //Method 2: use the constructor to do it
        String s1 = new String(stringBuffer3);
    }
} 

11.3.4 common methods of StringBuffer

public class StringBufferMethod {
    public static void main(String[] args) {
        StringBuffer s = new StringBuffer("hello");
        
        //increase
        s.append(',');// "hello,"
        s.append("Zhang Sanfeng");//"hello, Zhang Sanfeng"
        s.append("Zhao Min").append(100).append(true).append(10.5);//"hello, Zhang Sanfeng, Zhao Min 100true10.5"
        System.out.println(s);//"hello, Zhang Sanfeng, Zhao Min 100true10.5"
        
        //Delete
        /*
        * Delete characters at index > = start & & < end
        * Interpretation: delete characters from 11 to 14 [11, 14)
        */
        s.delete(11, 14);
        System.out.println(s);//"hello, Zhang Sanfeng, Zhao Min, true10.5"
        
        //change
        //Lao Han interprets and uses Zhou Zhiruo to replace the characters of index 9-11 [9,11]
        s.replace(9, 11, "Zhou Zhiruo");
        System.out.println(s);//"hello, Zhang Sanfeng, Zhou Zhiruo, true10.5"
        //Finds the index of the specified substring at the first occurrence of the string. If it is not found, it returns - 1
        int indexOf = s.indexOf("Zhang Sanfeng");
        System.out.println(indexOf);//6
        
        //insert
        //Lao Han interpreted that "Zhao Min" was inserted at the position with index 9, and the content with index 9 was automatically moved back
        s.insert(9, "Zhao Min");
        System.out.println(s);//"hello, Zhang Sanfeng, Zhao Min, Zhou Zhiruo, true10.5"
        
        //length
        System.out.println(s.length());//22
        System.out.println(s);
    }
}

11.3.5 practice

  1. public class StringBufferExercise01 {
        public static void main(String[] args) {
            String str = null;// ok
            StringBuffer sb = new StringBuffer(); //ok
            sb.append(str);//Depending on the source code, the bottom layer calls the appendNull of AbstractStringBuilder to convert the empty object into "null"
            System.out.println(sb.length());//4
            System.out.println(sb);//null
            //The following constructor will throw NullpointerException
            StringBuffer sb1 = new StringBuffer(str);//Look at the underlying source code super(str.length() + 16);
            System.out.println(sb1);
        }
    }
    

11.4 StringBuilder class

11.4.1 introduction

  1. A variable character sequence. This class provides an API compatible with StringBuffer, but does not guarantee synchronization (not thread safe). This class is designed to be used as a simple replacement for StringBuffer when the string buffer is used by a single thread. If possible, it is recommended to take this class first, as it is faster than StringBuffer in most implementations
  2. The main operations on StringBuilder are append method and insert method. These methods can be overloaded to receive any type of data

11.4.2 common methods

The methods of StringBuilder and StringBuffer are the same

11.4.3 comparison of string, StringBuffer and StringBuilder

  1. StringBuilder and StringBuffer are very similar. They both represent variable character sequences, and the method is the same

  2. String: immutable character sequence with low efficiency but high reuse rate

  3. StringBuffer: variable character sequence, high efficiency (addition and deletion), thread safety

  4. StringBuilder: variable character sequence, with the highest efficiency and unsafe thread

  5. String instructions:

    1. String s = "a";	//Created a string
      s += "b";	//In fact, the original "a" string has been discarded, and now a new string s+"b" (i.e. "ab") has been generated
      //If you perform these operations to change the string content multiple times, it will cause a large number of copy string objects to remain in memory and reduce efficiency.
      //If such an operation is placed in a loop, it will greatly affect the performance of the program
      //Conclusion: if we make a lot of changes to String, don't use String
      

11.4.4 selection of string, StringBuffer and StringBuilder

  1. If there are a lot of modification operations for strings, StringBuffer or StringBuilder is generally used
  2. If there are a lot of string modification operations and there is a single thread, use StringBuilder
  3. If there are a lot of string modification operations and there are multiple threads, use StringBuffer
  4. If our String is rarely modified and referenced by multiple objects, use String, such as configuration information

11.5 Math class

11.5.1 introduction

The Math class contains methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions

11.5.2 methods (all static)

There are many. Look at the documents, for example:

Modifier and TypeMethod and Description
static doubleThe return value of abs(double a) is the absolute value of double.
static floatabs(float a) returns the absolute value of the float value.
static intabs(int a) returns an absolute value of int.
static longabs(long a) returns a long absolute value.
static doubleacos(double a) returns the inverse cosine of the value; The angle returned is in the range of 0.0 to pi.
static intaddExact(int x, int y) returns the sum of its parameters. If the result overflows int, int will be thrown.
static longaddExact(long x, long y) returns the sum of its parameters. If the result overflows long, long will be thrown.
static doubleSin (double a) the sine of the return value; The return angle is in the range of pi / 2 to pi / 2.
static doubleatan(double a) returns the arctangent value of the value; The return angle is in the range of pi / 2 to pi / 2.
static doubleatan2(double y, double x) returns from rectangular coordinates (thetax, y) to polar coordinates (R, θ-).
static doublecbrt(double a) returns the cube root of the double value.
static doubleceil(double a) returns the minimum (closest to negative infinity) double value greater than or equal to the parameter, which is equal to a mathematical integer.

11.5.3 example

public class MathMethod {
    public static void main(String[] args) {
        //Common methods of Math (static method)
        //1.abs absolute value
        int abs = Math.abs(-9);
        System.out.println(abs);//9
        //2.pow exponentiation
        double pow = Math.pow(2, 4);//Two to the fourth power
        System.out.println(pow);//16
        //3.ceil rounds up and returns > = the smallest integer of the parameter (converted to double);
        double ceil = Math.ceil(3.9);
        System.out.println(ceil);//4.0
        //4. The floor is rounded down and returns < = the maximum integer of the parameter (converted to double)
        double floor = Math.floor(4.001);
        System.out.println(floor);//4.0
        //5.round math Floor (this parameter + 0.5)
        long round = Math.round(5.51);
        System.out.println(round);//6
        //6.sqrt calculation
        double sqrt = Math.sqrt(9.0);
        System.out.println(sqrt);//3.0
        //7.random number
        // Random returns a random decimal between 0 < = x < 1
        // Think: please write a random integer between a and B. A and B are integers, such as a = 2 and B = 7
        // That is to return a number x, 2 < = x < = 7
        // Math.random() * (b-a) returns 0 < = number < = b-a
        // (1) (int)(a) <= x <= (int)(a + Math.random() * (b-a +1) )
        // (2) Use specific numbers to introduce a = 2 and b = 7 to small partners
        // (int)(a + Math.random() * (b-a +1) ) = (int)( 2 + Math.random()*6)
        // Math.random()*6 returns 0 < = x < 6 decimals
        // 2 + Math.random()*6 returns 2 < = x < 8 decimals
        // (int)(2 + Math.random()*6) = 2 <= x <= 7
        // (3) The formula is (int)(a + Math.random() * (b-a +1))
        for(int i = 0; i < 100; i++) {
        System.out.println((int)(2 + Math.random() * (7 - 2 + 1)));
        }
        //Max, min returns the maximum and minimum values
        int min = Math.min(1, 9);
        int max = Math.max(45, 90);
        System.out.println("min=" + min);
        System.out.println("max=" + max);
    }
}

11.6 Arrays

11.6.1 common methods

Arrays contains a series of static methods for managing and manipulating arrays

  1. toString: returns the string form of the array
  2. Sort: sort (natural sort and custom sort)
  3. Binary search: the binary search method is used to search, and the order must be arranged
  4. copyOf: copies the specified array
  5. Fill: array element fill
  6. equals: compares whether two array elements are identical
  7. asList: convert array to list

11.6.2 example

  1. //toString
    Integer[] integers = {1, 20, 90};
    System.out.println(Arrays.toString(integers));//[1, 20, 90]
    
  2. //sort
    Integer arr[] = {1, -1, 7, 0, 89};
    //Default sort
    Arrays.sort(arr);
    //Custom sorting, through the incoming interface Comparator
    Arrays.sort(arr, new Comparator() {
        @Override
            public int compare(Object o1, Object o2) {
            Integer i1 = (Integer) o1;
            Integer i2 = (Integer) o2;
            return i2 - i1;
        }
    });
    
    1. When calling custom sort, two parameters are passed in

      1. Sorted array arr
      2. The anonymous internal class of Comparator interface is implemented, and the compare method is required to be implemented
    2. Arrays.sort(arr, new Comparator()); Private static void binarysort of TimSort class will be called (t [] A, int lo, int Hi, int start, comparator <? Super T > C) ()

    3. The code executed to the binarySort method will execute the compare() of the anonymous inner class we passed in according to the dynamic binding mechanism c.compare()

      1. while (left < right) {
            int mid = (left + right) >>> 1;
            if (c.compare(pivot, a[mid]) < 0)
            right = mid;
            else
            left = mid + 1;
        }
        
    4. )Whether the value returned by public int compare(Object o1, Object o2) > 0 or < 0 will affect the whole sorting result, which fully reflects the comprehensive use of interface programming + dynamic binding + anonymous internal classes. In the future, the use of underlying framework and source code will be very common

  3. //Combined bubbling + custom sorting
    public class ArraysSortCustom {
        public static void main(String[] args) {
            int[] arr = {12,2,-3,0,89,45};
            bubble(arr, new Comparator() {
                @Override
                public int compare(Object o1, Object o2) {
                    Integer i1 = (Integer) o1;
                    Integer i2 = (Integer) o2;
    //                return i1 - i2;   // Increasing
                    return i2 -i1;  //Diminishing
                }
            });
            System.out.println(Arrays.toString(arr));
        }
        public static void bubble(int[] arr, Comparator c) {
            int temp = 0;
            for (int i = 0; i < arr.length - 1; i++) {
                for (int j = 0; j < arr.length - 1 - i; j++) {
                    //Array sorting is determined by the value returned by c.compare(arr[j], arr[j + 1])
                    if(c.compare(arr[j], arr[j+1]) > 0) {
                        temp = arr[j];
                        arr[j] = arr[j+1];
                        arr[j+1] = temp;
                    }
                }
            }
        }
    }
    
  4. //binarySearch must be ordered
    Integer[] arr = {1, 2, 90, 123, 567};
    int index = Arrays.binarySearch(arr, 567);
    System.out.println("index=" + index);
    
  5. //copyOf
    Integer[] newArr = Arrays.copyOf(arr, arr.length);
    //1. Copy arr.length elements from arr array to newArr array
    //2. If the length of the copy is > arr.length, add null after the new array
    //3. If the copy length is < 0, an exception NegativeArraySizeException will be thrown
    //4. The bottom layer of this method uses system arraycopy()
    
  6. //fill
    Integer[] num = new Integer[]{9,3,2};
    Arrays.fill(num, 99);	
    //Using 99 to fill the num array can be understood as an element of the replacement principle
    System.out.println(Arrays.toString(num));	//[99, 99, 99]
    
  7. //equals compares whether the contents of two array elements are exactly the same
    Integer[] arr2 = {1, 2, 90, 123};
    boolean equals = Arrays.equals(arr, arr2);
    
  8. //asList converts a set of values into a list
    List asList = Arrays.asList(2,3,4,5,6,1);
    //1. asList method will convert (2,3,4,5,6,1) data into a List set
    //2. Returned asList compilation type list (Interface)
    //3. asList run type Java util. Arrays #arraylist is the name of the arrays class
    // Static inner classprivate static class ArrayList < E > extends abstractlist < E >
    // implements RandomAccess, java.io.Serializable
    

11.6.3 practice

public class ArrayExercise {
    public static void main(String[] args) {
        Book[] books = new Book[4];
        books[0] = new Book("The Dream of Red Mansion",100);
        books[1] = new Book("Journey to the West Prequel",90);
        books[2] = new Book("Romance of the Three Kingdoms",5);
        books[3] = new Book("Water Margin",300);
        //Sort by price
        sortBooks(books, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Book b1 = (Book) o1;
                Book b2 = (Book) o2;
                return (int)(b1.getPrice() - b2.getPrice());
            }
        });
        printBooks(books);
        //Sort by Title Length
        sortBooks(books, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Book b1 = (Book) o1;
                Book b2 = (Book) o2;
                return (int)(b1.getName().length() - b2.getName().length());
            }
        });
        printBooks(books);
    }

    public static Book[] sortBooks(Book[] books, Comparator c) {
        Book temp = null;
        for (int i = 0; i < books.length - 1; i++) {
            for (int j = 0; j < books.length - 1 - i; j++) {
                if(c.compare(books[j], books[j+1]) > 0) {
                    temp = books[j];
                    books[j] = books[j+1];
                    books[j+1] = temp;
                }
            }
        }
        return books;
    }
    public static void printBooks(Book[] books){
        for (Book book : books) {
            System.out.println(book);
        }
        System.out.println("===========================");
    }
}

class Book {
    private String name;
    private double price;

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

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return "title:" + name + ", Price:" + price + "element";
    }
}

11.7 System class

11.7.1 common methods

  1. Exit: exit the current program
  2. arraycopy: copy array elements, which is more suitable for underlying calls. Generally, array Copyof finish copying array
    1. Syntax: system arraycopy(src, srcPos, dest, destPos, length);
  3. currentTimeMillens: returns the number of milliseconds between the current time and 1970-01-01
  4. GC: run the garbage collection mechanism system gc()

11.7.2 example

//exit
System.exit(0);//exit(0) indicates that the program exits, 0 indicates a state, normal state

//arraycopy
int[] src = {1, 2, 3};
int dest = new int[3];
System.arraycopy(src, 0, dest, 0, 3);

//currentTimeMillens
System.out.println(System.currentTimeMillis());

11.8 BigInteger class and BigDecimal class

11.8.1 introduction

  1. BigInteger is suitable for storing large integers
  2. BigDecimal is suitable for saving floating-point numbers with higher precision

11.8.2 common methods

When adding, subtracting, multiplying and dividing BigInteger and BigDecimal, the corresponding method needs to be used, and + - * cannot be directly performed/

  1. Add: add
  2. Subtract: subtract
  3. Multiply: multiply
  4. Divide: divide

11.8.3 example

  1. //BigInteger
    BigInteger bigInteger = new BigInteger("23788888899999999999999999999");
    BigInteger bigInteger2 = new BigInteger("10099999999999999999999999999999999999999999999999999999999999999999999999999999999");
    System.out.println(bigInteger);
    //plus
    BigInteger add = bigInteger.add(bigInteger2);
    System.out.println(add);
    //reduce
    BigInteger subtract = bigInteger.subtract(bigInteger2);
    System.out.println(subtract);
    //ride
    BigInteger multiply = bigInteger.multiply(bigInteger2);
    System.out.println(multiply);
    //except
    BigInteger divide = bigInteger.divide(bigInteger2);
    System.out.println(divide);
    
  2. //BigDecimal 
    BigDecimal bigDecimal = new BigDecimal("1999.111111111199999999922222228888");
    BigDecimal bigDecimal2 = new BigDecimal("3");
    System.out.println(bigDecimal);
    System.out.println(bigDecimal.add(bigDecimal2));
    System.out.println(bigDecimal.subtract(bigDecimal2));
    System.out.println(bigDecimal.multiply(bigDecimal2));
    //System.out.println(bigDecimal.divide(bigDecimal2));// The exception ArithmeticException may be thrown because the result is an infinite circular decimal
    //Solution: when calling the divide method, specify the precision BigDecimal.ROUND_CEILING
    //When specified, if there is an infinite circular decimal, the precision of the numerator will be retained
    System.out.println(bigDecimal.divide(bigDecimal2, BigDecimal.ROUND_CEILING));
    

11.9 date category

11.9.1 first generation date category

  1. Date: accurate to milliseconds, representing a specific moment. Many methods have been abandoned
  2. SimpleDateFormat: a class that formats and parses dates. It allows formatting (date - > text), parsing (text - > date), and normalization
letterDate or time elementexpressExamples
GEra designatorTextAD
yYearYear1996; 96
YWeek yearYear2009; 09
MMonth in year (context sensitive)MonthJuly; Jul; 07
LMonth in year (standalone form)MonthJuly; Jul; 07
wWeek in yearNumber27
WWeek in monthNumber2
DDay in yearNumber189
dDay in monthNumber10
FDay of week in monthNumber2
EDay name in weekTextTuesday; Tue
uDay number of week (1 = Monday, ..., 7 = Sunday)Number1
aAm/pm markerTextPM
HHour in day (0-23)Number0
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978
zTime zoneGeneral time zonePacific Standard Time; PST; GMT-08:00
ZTime zoneRFC 822 time zone-0800
XTime zoneISO 8601 time zone-08; -0800; -08:00

Example:

public class Date01 {
    public static void main(String[] args) throws ParseException {
        //1. Get the current system time
        //2. The Date class here is in Java Util package
        //3. The default output date format is foreign, so it is usually necessary to convert the format
        Date d1 = new Date(); //Get current system time
        System.out.println("current date=" + d1);
        Date d2 = new Date(9234567); //Gets the time by specifying the number of milliseconds
        System.out.println("d2=" + d2); //Gets the number of milliseconds corresponding to a certain time
        
        //1. Create a SimpleDateFormat object and specify the corresponding format
        //2. The letters used in the format here are well specified and can't be scribbled
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day hh:mm:ss E");
        String format = sdf.format(d1); // Format: converts the date to a string in the specified format
        System.out.println("current date=" + format);
        
        //1. You can convert a formatted String to the corresponding Date
        //2. When the Date is still output, it is still in the form of foreign countries. If you want to output in the specified format, it needs to be converted
        //3. The format of sdf used in String - > date should be the same as that of the String you gave, otherwise a conversion exception will be thrown
        String s = "1996 January 1, 2010:20:30 Monday";
        Date parse = sdf.parse(s);
        System.out.println("parse=" + sdf.format(parse));
    }
}

11.9.2 second generation date category

  1. The second generation of date class is Calender class (calendar)
  2. Calendar class is an abstract class, which is associated with a group of specific moments, such as YEAR, MONTH and day_ OF_ The conversion between calendar fields such as MONTH and HOUR provides some methods, and provides some methods for operating calendar fields (such as obtaining the date of the next week).

Example:

public class Calendar_ {
    public static void main(String[] args) {
        
        //1. Calendar is an abstract class, and the constructor is private
        //2. You can get the instance through getInstance()
        //3. Provide a large number of methods and fields to programmers
        //4. Calendar does not provide corresponding formatted classes, so programmers need to combine them to output (flexible)
        //5. If we need to get the time in 24-hour decimal, calendar Hour = = changed to = > calendar HOUR_ OF_ DAY
        Calendar c = Calendar.getInstance(); //Create a calendar object. / / it's easy and free
        System.out.println("c=" + c);
        //2. Get a calendar field of the calendar object
        System.out.println("Year:" + c.get(Calendar.YEAR));
        // Why do you want + 1 here? When Calendar returns the month, it starts with 0
        System.out.println("Month:" + (c.get(Calendar.MONTH) + 1));
        System.out.println("Date:" + c.get(Calendar.DAY_OF_MONTH));
        System.out.println("Hours:" + c.get(Calendar.HOUR));
        System.out.println("minute:" + c.get(Calendar.MINUTE));
        System.out.println("Seconds:" + c.get(Calendar.SECOND));
        //Calender has no special formatting method, so programmers need to combine the display by themselves
        System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" +
        c.get(Calendar.DAY_OF_MONTH) +
        " " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) );
    }
}

11.9.3 third generation date category

11.9.3.1 shortage of the first two generations

Most of the methods of the Date class are in jdk1 1. The Calendar class is discarded after being introduced. There are also problems with Calendar:

  1. Variability: classes like date and time should be immutable
  2. Offset: the year in Date starts from 1900 and the month starts from 0
  3. Formatting: formatting is only useful for Date, not Calendar
  4. They are not thread safe
  5. Every 1 second, no more than 2 seconds

11.9.3.2 LocalDate,LocalTime,LocalDateTime

JDK8 adds LocalDate, LocalTime and LocalDateTime

  1. LocalDate only contains date. You can get the date field
  2. LocalTime only contains time. You can get the time field
  3. LocalDateTime contains date + time. You can get the date and time fields

11.9.3.3 DateTimeFormatter format date class

Similar to SimpleDateFormat

Syntax:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
String str = dtf.format(Time object);

11.9.3.4 example

public class LocalDate_ {
    public static void main(String[] args) {
        //Third generation date
        //1. Use now() to return the object representing the current date and time
        LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()
        System.out.println(ldt);
        //2. Use DateTimeFormatter object to format
        // Create DateTimeFormatter object
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = dateTimeFormatter.format(ldt);
        System.out.println("Formatted date=" + format);
        System.out.println("year=" + ldt.getYear());
        System.out.println("month=" + ldt.getMonth());
        System.out.println("month=" + ldt.getMonthValue());
        System.out.println("day=" + ldt.getDayOfMonth());
        System.out.println("Time=" + ldt.getHour());
        System.out.println("branch=" + ldt.getMinute());
        System.out.println("second=" + ldt.getSecond());
        LocalDate now = LocalDate.now(); //You can get the date
        LocalTime now2 = LocalTime.now();//Get the time to minute and second
        //plus and minus methods are provided to add or subtract the current time
        //Look at 890 days later, when is the year, day, hour, minute and second
        LocalDateTime localDateTime = ldt.plusDays(890);
        System.out.println("890 Days later=" + dateTimeFormatter.format(localDateTime));
        //See what time it was 3456 minutes ago, and output the year, month, day, hour, minute and second
        LocalDateTime localDateTime2 = ldt.minusMinutes(3456);
        System.out.println("3456 Date minutes ago=" + dateTimeFormatter.format(localDateTime2));
    }
}

11.9.3.5 Instant timestamp

Similar to Date

Provides a series of methods for converting and Date classes

  1. Instant -> Date :

    1. Date date = Date.from(instant);
      
  2. Date ->Instant :

    1. Instant instant = date.toInstant();
      

Example:

public class Instant_ {
    public static void main(String[] args) {
        //1. Get the object representing the current timestamp through the static method now()
        Instant now = Instant.now();
        System.out.println(now);
        //2. from can be used to convert Instant to Date
        Date date = Date.from(now);
        //3. Date can be converted into an Instant object through toInstant() of date
        Instant instant = date.toInstant();
    }
}

11.10 practice

  1. /**
     * Invert the specified part of the string, such as "abcdef" to "aedcbf"
     * Write the method public static String reverse(String str, int start, int end)
     */
    public class Exercise9_01 {
        public static void main(String[] args) {
            String str = "abcdef";
            try {
                System.out.println(reverse(str, 1, 4));
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        public static String reverse(String str, int start, int end) {
            if (str == null || str.length() == 0 || start >=end || start < 0 || end >= str.length()) {
                throw new RuntimeException("parameter is incorrect");
            }
            StringBuffer sb = new StringBuffer(str);
            char temp = ' ';
            while(start < end) {
                temp = sb.charAt(start);
                sb.setCharAt(start, sb.charAt(end));
                sb.setCharAt(end, temp);
                start++;
                end--;
            }
            return sb.toString();
        }
    }
    
  2. /**
     * Enter the user name, password and email address. If the information is entered successfully, you will be prompted that the registration is successful. Otherwise, an exception object will be generated
     * requirement:
     * 1.User name length is 2, 3 or 4
     * The password length is 6 and all numbers are required
     * The mailbox contains @ and And @ in front
     */
    public class Exercise9_02 {
        public static void main(String[] args) {
            String name = "tom";
            String pwd = "123456";
            String email = "tom@163.com";
            try {
                userRegister(name, pwd, email);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        public static void userRegister(String name, String pwd, String email) {
            if (name == null || pwd == null || email == null ||
                    name.length() == 0 || pwd.length() == 0 ||
                	email.length() == 0) {
                throw new RuntimeException("Parameter cannot be empty");
            }
            //Judge whether the user name length is 2, 3 or 4
            int nameLen = name.length();
            if (!(nameLen >= 2 && nameLen <= 4)) {
                throw new RuntimeException("User name length is 2, 3 or 4");
            }
            //Judge whether the password length is 6 and whether it is all numbers
            if (!(pwd.length() == 6 && isDigital(pwd))) {
                throw new RuntimeException("The password length is 6 and all numbers are required");
            }
            //Determine whether the mailbox contains @ and And @ in front
            int atPos = email.indexOf('@');
            int pointPos = email.indexOf('.');
            if (!(atPos > 0 && pointPos > atPos)) {
                throw new RuntimeException("Mailbox contains@and.also@stay.front");
            }
            //If the front pass, the registration is successful
            System.out.println("Registration succeeded!");
            System.out.println("Welcome," + name);
        }
    
        //Judge whether the string is a number
        public static boolean isDigital(String str) {
            char[] chars = str.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                if (chars[i] < '0' || chars[i] > '9') {
                    return false;
                }
            }
            return true;
        }
    }
    
  3. /**
     * Write a Java program in the form of William Jefferson Clinton,
     * To Clinton, William Print out in the form of J
     * Among them J is the initial capital of the middle word
     */
    public class Exercise9_03 {
        public static void main(String[] args) {
            String name = "William Jefferson Clinton";
            try {
                System.out.println(reverse(name));
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        public static String reverse(String name) {
            if (name == null || name.length() == 0) {
                throw new RuntimeException("Name cannot be empty");
            }
            String[] names = name.split(" ");
            if (names.length != 3) {
                throw new RuntimeException("The input format is incorrect");
            }
            return String.format("%s,%s .%s",names[2],names[0],names[1].toUpperCase().charAt(0));
        }
    }
    
  4. /**
     * Input the string and judge how many uppercase letters, lowercase letters and numbers there are
     */
    public class Exercise9_04 {
        public static void main(String[] args) {
            String str = "Ab86dDc3";
            try {
                count(str);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        public static void count(String str) {
            if (str == null || str.length() == 0) {
                throw new RuntimeException("String cannot be empty");
            }
            int upperCaseCount = 0;
            int lowerCaseCount = 0;
            int digitCount = 0;
            char[] chars = str.toCharArray();
            for (char aChar : chars) {
                if (Character.isUpperCase(aChar)) {
                    upperCaseCount++;
                } else if (Character.isLowerCase(aChar)) {
                    lowerCaseCount++;
                } else if (Character.isDigit(aChar)) {
                    digitCount++;
                }
            }
            System.out.println("character string:"+str+"have"+
                    upperCaseCount+"A capital letter,"+
                    lowerCaseCount+ "Lower case letters,"+
                    digitCount+"Number");
        }
    }
    

Topics: Java