1. Common methods of StringBuilder class
- The StringBuilder append (any type) parameter is appended to a string, and becomes a string no matter what the parameter is written It is equivalent to the + operation in the string
public static void builderAppend(){ StringBuilder builder = new StringBuilder(); //The append method appends a string builder.append(100); builder.append(5.8); builder.append(true); System.out.println("builder = " + builder); }
-
Method call chain, chain programming:
Chain programming: ensure that the return value of a method is an object, and then use the calling method called by this object: object Method () Method () Method
public static void builderAppend2(){ StringBuilder builder = new StringBuilder(); //The return value of the method append() is StringBuilder //return this the return value is this builder.append("hehe").append(false).append(1.5).append(1); //The result of execution is the builder object. Continue to use the builder object to call the method System.out.println("builder = " + builder); }
-
StringBuilder insert(int index, any type) can insert parameters of any type into the string buffer and specify the index
/** * StringBuilder Class, specify the location and insert elements */ public static void builderInsert(){ StringBuilder builder = new StringBuilder(); builder.append("bcdef"); //On the specified index, add the string, the original character and postpone it builder.insert(2,"QQ"); System.out.println("builder = " + builder); }
-
Other methods of StringBuilder class
- int length() returns the length of the string buffer
- StringBuilder delete(int start,int end) deletes the characters in the buffer, including the beginning index and not the end index
- void setCharAt(int index, char ch) modifies the characters on the specified element
- StringBuilder reverse() flips the string
1.1 conversion between StringBuilder object and String object
- Convert String object to StringBuilder object String -- > StringBuilder
- Construction method of StringBuilder class StringBuilder(String str)
- Append method append(String str)
/** * String -> StringBuilder */ public static void stringToStringBuilder(){ //Construction method StringBuilder builder = new StringBuilder("abc"); //Object's method append builder.append("hello"); }
- Convert StringBuilder object to String object StringBuilder - > String
- StringBuilder's method toString()
- Construction method of String class
/** * StringBuilder -> String */ public static void stringBuilderToString(){ StringBuilder builder = new StringBuilder(); builder.append("I'm a buffer of strings"); //Convert the builder object into a String object and call the method toString() of the builder object String str = builder.toString(); System.out.println(str); //Construction method of String class String s = new String(builder); System.out.println(s); }
2. System class
System class: defined in Java Lang package
A large number of commonly used fields (member variables) and methods are defined. This class cannot instantiate objects and cannot new. All members in the class are statically decorated, and the class name is called directly
All static members, no object creation, class name call Construction method private modification
2.1 method of system class
-
static long currentTimeMillis() returns the number of milliseconds elapsed from 0:00 midnight on January 1, 1970 to the time when your program runs. 1000 milliseconds = 1 second
/** * static long currentTimeMillis() * Returns the number of milliseconds elapsed from 0:00 midnight on January 1, 1970 to the time when your program is running, * 1000 Ms = 1 second */ public static void systemCurrentTimeMillis(){ long timeMillis = System.currentTimeMillis(); System.out.println("timeMillis = " + timeMillis); }
-
Static void arraycopy (object SRC, int srcpos, object DeST, int destpos, int length) copies the elements of the array
- src: data source to be assigned, source array
- srcPos: start index of source array
- dest: target array to copy
- Index of target array: potdests
- length: the number of elements to copy
public static void systemArraycopy(){ int[] src = {1,3,5,7,9}; int[] dest = {2,4,6,8,0}; //Assignment of array elements: copy 3,5 in src array to dest array and start with 0 index System.arraycopy(src,1,dest,0,2); for(int x = 0 ; x < src.length ;x++ ){ System.out.println(dest[x]); } }
- static Properties getProperties() returns the current operating system properties
/** * static Properties getProperties() Returns the current operating system properties * System.getProperty(String (key name) */ public static void systemGetProperties(){ Properties properties = System.getProperties(); System.out.println(properties); String str = System.getProperty("os.name"); System.out.println(str); }
3. Math class
-
static double PI Pi Pi
-
static double E base of natural number
-
static int abs(int a) returns the absolute value of the parameter
-
static double ceil(double d) returns the smallest integer greater than or equal to the parameter
-
static double floor(double d) returns the maximum integer less than or equal to the parameter
-
static long round(double d) rounds the parameter
-
Static double pow (double a, double b) power b of a
-
static double random() returns a random number between 0.0 and 1.0
-
Square root of static double sqrt(double d) parameter
public static void main(String[] args) { // System.out.println("Math.PI = " + Math.PI); // System.out.println("Math.E = " + Math.E); //static int abs(int a) returns the absolute value of the parameter System.out.println(Math.abs(-6)); //static double ceil(double d) returns the smallest integer greater than or equal to the parameter System.out.println(Math.ceil(12.3)); //Take an integer up //static double floor(double d) returns the maximum integer less than or equal to the parameter System.out.println("Math.floor(5.5) = " + Math.floor(5.5));//Take an integer down //static long round(double d) rounds the parameter long round = Math.round(5.5); //Take integer part parameter + 0.5 System.out.println("round = " + round); //Static double pow (double a, double b) power b of a System.out.println("Math.pow(2,3) = " + Math.pow(2, 3)); //Square root of static double sqrt(double d) parameter System.out.println("Math.sqrt(4) = " + Math.sqrt(3)); // static double random() returns a random number between 0.0 and 1.0 for(int x = 0 ; x < 10 ; x++){ System.out.println(Math.random()); //Pseudo random number } }
4. Array related operations
4.1 flip of array
An example of so-called array flipping: the original array {1,2,3,4} is {4,3,2,1} after flipping
Array flip is not equal to flashback traversal
The exchange of element positions in the array and the transposition of the array, with the help of a variable
Core problem: at the exchange position of the farthest element in the array
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG rttnqlfe-1646483305640) (IMG / array flip 1.JPG)]
/** * Flip of array */ public static void arrayReverse(){ int[] arr = {1,2,7,5,0,22,3,4}; //Farthest element, swap location (using third-party variables) for(int min = 0 , max = arr.length -1; min < max ; min++ ,max-- ){ int temp = arr[min] ;//Record the element on the smallest index of the array arr[min] = arr[max] ; //The element on the largest index of the array is assigned to the position of the smallest element arr[max] = temp; } //Traverse to see the result for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }
4.2 binary (half) search method of array
- Basic search method of array: judge whether an element exists in the array
- Traverse the array and find it
- Binary search method improves efficiency: the premise is that the array must be orderly
[the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-7sOjekAt-1646483305641)(img / binary query schematic diagram. JPG)]
/** * Binary search method of array * Returns the index of the searched element in the array. If not, it returns a negative number */ public static int binarySearch(int[] arr,int key){ int min = 0 ; //Minimum index of the array int max = arr.length - 1; //Maximum index of the array int mid ;//The index of the middle position after the array is halved //The cycle is halved, the number of times is uncertain, and the while cycle //Condition,, the minimum index cannot exceed the maximum index while (min <= max){ //Halve mid = (min + max) / 2; //The halved mid is used as the index to take out the elements of the array and compare with the keyword if (key > arr[mid]) //Move minimum index min = mid + 1; else if (key < arr[mid]) //Move maximum index max = mid - 1; else { //Found, return index return mid; } } return -1; }
4.3 sorting of arrays
In an unordered array, the elements are sorted in ascending order by default efficiency
Array sorting: the position exchange of elements in memory is the least efficient
Select sort, bubble (select optimization), insert sort, half sort, Hill sort, quick sort
4.3.1 bubble sorting
Core idea: compare transposition between elements Comparison method of bubble sorting: comparison of adjacent elements
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-xcrvwqkr-1646483305642) (bubble sorting of img / array. JPG)]
/** * Sorting implementation */ public static void bubbleSort(int[] arr){ //External circulation, fixed times for (int i = 0 ; i < arr.length ; i++){ //Internal circulation, decreasing operation shall be carried out every time for (int j = 0 ; j < arr.length - i - 1; j++){ //j 0-6 //Comparative transposition if (arr[j] > arr[j + 1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }
4.3.2 selection and sorting optimization
Optimization: it is not necessary to transpose after each comparison to obtain the maximum value, and use this maximum value in the transposition value
/** * Optimization of selection sorting * Maximum value acquisition: * Use elements * Use index */ public static void selectSort(int[] arr){ //Gets the latest value of the array for (int i = 1 ; i < arr.length ;i++){ //Define variables to hold the first element of the array int min = arr[i-1]; //[1-1 = 0] //Define record minimum index int minIndex = i-1; for(int j = i ; j < arr.length ; j++){ if (min > arr[j]){ //Index of records minIndex = j; //Record minimum min= arr[j]; } } //Location exchange if (minIndex != (i-1)){ int temp = arr[i-1]; arr[i-1] = arr[minIndex]; arr[minIndex] = temp; } } }
4.4 Arrays tools
java. The util package defines the class Arrays, a tool class for array operations Class cannot create an object. It is called statically directly
- Static method of Arrays class
- Static void sort (array) sorts arrays in ascending order (by far the most efficient)
- Static int binarysearch (array, search keyword) performs binary search on the array
- Static void fill (array, filled element)
- Static string toString (array) returns the array string representation
- The static List asList(T... t) element is converted into a List set
public static void main(String[] args) { int[] arr = {1,5,9,10,15,22,27,30}; //arrayToString(arr); // arraySort(arr); // System.out.println(Arrays.toString(arr)); int index = arrayBinarySearch(arr,5); System.out.println(index); arrayFill(); } /** * fill Fill array */ public static void arrayFill(){ int[] arr = {1,2,3,4,5}; Arrays.fill(arr,6); System.out.println(Arrays.toString(arr)); } /** * static int binarySearch(Binary search method for array * Returns the index of the element that appears in the array * If the element does not exist, return (- insertion point - 1) * key : Put it in the array to ensure orderly */ public static int arrayBinarySearch(int[] arr,int key){ int index = Arrays.binarySearch(arr, key); return index; } /** * static void sort(Array) sort arrays in ascending order (by far the most efficient) */ public static void arraySort(int[] arr){ Arrays.sort(arr); } /** * static String toString(Array) returns an array string representation * toString Internal automatic traversal array */ public static void arrayToString(int[] arr){ String str = Arrays.toString(arr); System.out.println(str); }
5. String related operations
5.1 string flipping
Arrays can be converted into strings, and strings can also be converted into arrays (flipping numbers)
/** * Another implementation of flipping strings */ public static String stringReverse2(String str){ //str to StringBuilder //StringBuilder builder = new StringBuilder(str); // builder.reverse(); //String buffer converted to string return //return builder.toString(); return new StringBuilder(str).reverse().toString(); } /** * Flip string * Pass the string and return the flipped string */ public static String stringReverse(String str){ //Convert string to array char[] chars = str.toCharArray(); //Flip array for(int min = 0 ,max = chars.length - 1; min <= max ; max--,min++){ char temp = chars[min]; chars[min] = chars[max]; chars[max] = temp; } //Convert array to string return new String(chars); }
5.2 custom trim()
Remove the spaces on both sides of the string
" abcd efg " ==>"abcd efg"
/** * Custom method (trim) * " abcde fg " * "abcde fg " */ public static String myTrim(String str){ //Remove the space at the beginning of the string and replace with the method str = str.replaceFirst(" +",""); //Judge whether the string ends with a space while (str.endsWith(" ")){ //"abcde fg1" //Intercept string str = str.substring(0,str.length()-1); } return str; }
5.3 number of characters
Requirements: specify the string "asdfg3435erAAEExc", statistics department, lowercase letters, uppercase letters and numbers, and how many times they appear respectively, regardless of other characters
Statistical case: counter thought variable++
Implementation idea: replace the string with an array, take out each element, and count the ASCII code respectively
/** * Counts the number of occurrences of characters and numbers in a string */ public static void stringCount(String str){ if (str == null) return; //Define three counter variables int upper = 0 , lower = 0 , number = 0; //Convert string to array char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { //Take out each element char ch = chars[i]; //Determine the ASCII range of ch characters if ( ch >= 'A' && ch <= 'Z') //capital upper ++; else if ( ch >= 'a' && ch <= 'z') //Lowercase letters lower ++; else if (ch >= '0' && ch <= '9'){ //number number ++; } } System.out.println("capital:"+upper); System.out.println("Lowercase letters:"+lower); System.out.println("number:"+number); }