1. Tool classes
1.1. Design of tool classes
Many methods that accomplish common functions are extracted and classified into classes called utility classes
How to design tool classes (two types)
-
All utility methods use the public static modifier **
In this case, only the name of the utility class is used to call the utility method, and the constructor of the utility class must be privatized to prevent the creation of the object of the utility class to call the static method
-
If the tool method does not use the static modifier
The object of the utility class must be used to call the method of the utility class, and the utility class must be designed as a singleton pattern
1.1.1. Public static methods
Requirement 1: Design an array utility class using public static methods
ArraysUtils class
public void ArraysUtils{
//1. Privatize the constructor first to prevent the instantiated object
private ArraysUtils(a){}//2. Write tool methods
public static void sort(a){
System.out.println("I'm the sorting method.")}public static void print(a){
System.out.println("I'm print method method.")}}Copy the code
TsstDemo class
public class TsstDemo{
public static void main(String[] args){
ArraysUtils.sort()
}
}
Copy the code
The caller must pass the utility class name. The tool method name completes the call
1.2. Singleton mode
Design Pattern
Is a set of code design lessons that have been used over and over again. Design patterns are used to make code reusable, easier for others to understand, and reliable. There are 23 common design patterns in Java
Singleton Design Pattern
The most common and simplest design patterns, singletons, fall into two categories: slacker and hungrier
purpose
Ensure that there is only one instance of a class in the entire application
Steps (take hangry as an example)
- Privatize the constructor itself, preventing the outside world from instantiating objects through the constructor
- In this class, you create an object
- Expose a public static method to return its own object
public class SingletonUtil{
// 1. Privatize the constructor first to prevent the instantiated object
private SingletonUtil(a){}//2. Create an object
private static SingletonUtil instance = new SingletonUtil();
//3. Expose the method to the outside world to return the created object
public static SingletonUtil getInstance(a){
return instance;
}
public void sort(a) {
System.out.println("Sort operation");
}
public void binarySearch(a) {
System.out.println(Binary search operation); }}Copy the code
Call method:
SingletonUtil.getInstance().sort();
Copy the code
2. Packaging
The basic data types in Java have no methods and attributes, and the purpose of the wrapper class is to have methods and attributes to achieve Object interaction. Numeric wrapper classes inherit from Number, while character and Boolean classes inherit from Object
2.1 basic types of packaging classes
Mapping between basic data types and wrapper classes:
Basic types of | For the packaging class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
2.1.1, Integer
Integer encapsulates the basic data type value of type int and provides methods to manipulate int values and interchangeably String values.
2.1.1.1、Integer >> int
Integer i = new Integer();
int intValue = i.intValue();
Copy the code
2.1.1.2, int >> Integer
int i = 20;
Integer integer = Integer.valueOf(i);
Copy the code
2.1.1.3, Integer > > String
int i = 30;
Stirng value = Integer.valueOf(i);
Copy the code
2.1.1.4, String >> Integer
Integer i = Integer.valueOf("3");
Copy the code
2.1.1.5, String >> int
int i = Integer.parseInt("134");
Copy the code
2.1.1.6, int >> String
String str = Integer.toString(134);
Copy the code
2.2 Unpacking and packing
2.2.1, packing,
Convert the base data type to the appropriate wrapper class object
Integer num2 = Integer.valueOf(17);
Copy the code
2.2.2, split open a case
Converts wrapper objects to their corresponding primitive data types
int val = num3.intValue();
Copy the code
2.2.3 Automatic unpacking and packing
Automatic packing and unpacking are provided from JDK5, we no longer need to manually unpacking and unpacking frequently
Integer num4 = 17; // Box operation
int val2 = num4; // Unpacking operation
Copy the code
2.3 cache design
In terms of performance, storing frequently used data in the cache area can improve performance without creating new objects each time
Cache scope for common wrapper types
- Byte, Short, Integer, Long: cache range [-128,127]
- Character: cache range [0,127]
/ / the first
Integer i1 = new Integer(123);
Integer i2 = new Integer(123);
System.out.println(i1 == i2);// false because a new object is created in the heap
/ / the second
Integer i3 = Integer.valueOf(123);
Integer i4 = Integer.valueOf(123);
System.out.println(i3 == i4);[-128,127]; // true
/ / the third kind
Integer i5 = 123; // The bottom level is equivalent to the second
Integer i6 = 123;
System.out.println(i5 == i6);// true
Copy the code
Pay attention to
-
If the numbers are not in the cache, false is returned
-
If you want to compare the data of two objects for equality, you must use the equals method to determine whether == is the same block of memory and equals is the same block of memory
-
The default value of the int type is 0, and the default value of Integer is null. Integer is recommended in development because it can represent both 0 and NULL
2.4, BigDecimal
Neither float nor double can represent exact decimals, a problem that can be solved by using the BigDecimal class, which is used to process money or arbitrary precision data
2.4.1 Basic operations
BigDecimal cannot perform assignments and operations directly; it can only pass data through constructors, which must be string constructors
System.out.println(0.09 + 0.01);
Copy the code
We run this code, and the result is
It will generate a value that is infinitely close to 0.1, which means that this is not suitable for us to calculate
BigDecimal num1 = new BigDecimal(0.09);
BigDecimal num2 = new BigDecimal(0.01);
System.out.println(num1.add(num2));
Copy the code
BigDecimal cannot turn on high-precision mode if we do not use a string constructor
BigDecimal num3 = new BigDecimal("0.09");
BigDecimal num4 = new BigDecimal("0.01");
System.out.println(num3.add(num4));
Copy the code
Finally, the correct result is run. It is necessary to use the string constructor to enable the high-precision calculation mode
2.4.2 Precision control
We need to carry out precision control operations in the calculation
RoundingMode RoundingMode.HALF_UP Round */
BigDecimal num5 = new BigDecimal("0.987");
BigDecimal bigDecimal = num5.setScale(2, RoundingMode.HALF_UP);
System.out.println(bigDecimal);
Copy the code
2.4.3 Irrational number problem
/* java.lang.ArithmeticException Non-terminating decimal expansion; no exact representable decimal result. Error cause: Not enough (3.333333333... 333...). * /
BigDecimal num1 = new BigDecimal("10.0");
BigDecimal num2 = new BigDecimal("3.0");
BigDecimal r2 = num1.divide(num2,3,RoundingMode.HALF_UP);
System.out.println(r2);
Copy the code
3. String
A string (sequence of characters), which means that multiple characters are arranged in a certain order
Strings can be divided into two categories, depending on whether their content is mutable or not:
- Immutable String -String: Once a String object is created, its contents cannot be changed. Once the contents are changed, it becomes a new object
- Variable string – StringBuilder/StringBuffer: is variable, after when creating the object, the content of the object can be sent to change, when the content changes, object remains the same
3.1, String
The String type represents a String, and all String literals (such as “ABC”) in Java programs are implemented as instances of this class. The bottom layer of a String is in the form of a character array. A String is a wrapper class for a character array and provides methods to manipulate its wrapped character array in read-only form
3.1.1. String Memory Diagram
3.1.1.1. Create by literal
Memory map created by literals String str1 = “ABC”
Strings created by literals are allocated in the constant pool, so literal strings are constants; Their values cannot be changed after creation, because strings are immutable and can be shared
3.1.1.2. Create by instantiating objects
Memory map created by instantiating objects
3.1.1.3,
The String class represents an immutable String. Once a String object is created, its contents cannot be changed. Once the contents are changed, it becomes a new object
String str = "hello";
str = str + "word";
Copy the code
3.1.2. Null values for Strings
// reference is null
String str1 = null; // No initialization, no memory allocated.
// Content is an empty string
String str2 = ""; // Initialized, allocated memory space, but no content
Copy the code
3.1.3 Common methods of string
3.1.3.1, = =
== Compares whether it is the same reference, that is, whether it is the same object
3.1.3.2, equals
== compares whether the values are equal
3.1.3.3 String Search
contains
// String lookup
String str3 = "hello world";
// Check whether it contains
System.out.println(str3.contains("w"));
Copy the code
The Java Api documentation describes the Contains method:
原 文 : Returns true if and only if this string contains the specified sequence of char values
endsWith/startsWith
// Determine whether the suffix/prefix is xx
String str4 = "icon20191101.png";
System.out.println(str4.endsWith(".png"));
System.out.println(str4.startsWith("icon"));
Copy the code
The Java Api documentation describes the startsWith/endsWith methods:
Tests whether this string begins with the specified prefix
Tests whether the substring of this string starting at the specified index starts with the specified prefix
Tests whether this string ends with the specified suffix
indexOf
String str5 = "helloworld123";
System.out.println(str5.indexOf('o'));
System.out.println(str5.indexOf('o'.5));
Copy the code
The Java Api documentation describes the indexOf method:
Returns the index in the string in which the specified character is first encountered
Returns the index of the string in which the specified character first occurs, starting the search at the specified index
3.1.3.4. String Replacement
replace
String str1 = "helloworld123";
// Replace the given character
String newStr1 = str1.replace("h"."H");
System.out.println(newStr1);
// Replace the given string
// String newStr2 = str1.replace("hello", "HELLO");
String newStr2 = str1.replace("hello"."");
System.out.println(newStr2);
Copy the code
Returns a string that is the result of replacing all occurrences of oldChar in this string with newChar.
原 文 : Replaces each substring in the string that matches the given regular expression with the given substitution
3.1.3.5 String Splitting
// String delimiters
String str1 = "186-2001-1234";
String[] strArr = str1.split("-");
System.out.println(Arrays.toString(strArr));
// If more than one delimiter can be placed in [], separate the delimiters with Spaces
String str = "a; b:c; d:w";
System.out.println(Arrays.toString(str.split("[: :]")));
Copy the code
原 文 : Split this string around the matches of the given regular expression
3.1.3.6. Find strings
substring
String str1 = "helloworld";
System.out.println(str1.substring(5));
If the end index is not written, the default value is the last digit. If the end index is not written, the default value is the last digit
System.out.println(str1.substring(0.5));
Copy the code
Returns a string that is a substring of the string
3.1.3.7. Get characters at specified positions
// Get the character of the position
String str1 = "hello";
char c = str1.charAt(0);
System.out.println(c);
Copy the code
Returns the character value at the specified index
3.1.3.8 string Connection
// String concatenation
String str2 = "abc";
String str3 = "123";
System.out.println(str2.concat(str3));
Copy the code
Concatenate the specified string to the end of the string
3.1.3.9 String Length
String str4 = "123";
System.out.println(str4.length());
Copy the code
3.1.3.10. Check whether the string is empty
String str4 = "123";
System.out.println(str4.length());
Copy the code
3.1.3.11. Case conversion
// Case conversion
String str5 = "Hello";
System.out.println(str5.toUpperCase());/ / caps
System.out.println(str5.toLowerCase());/ / lowercase
Copy the code
3.1.3.12. Remove Spaces
String str = " hello ";
System.out.println(str.length());
String trim = str.trim();
System.out.println(trim.length());
Copy the code
Returns a string of that value with all leading and trailing whitespace removed
3.1.3.13. Check whether the string is not empty
public static boolean hasLength(String str) {
returnstr ! =null&&!"".equals(str.trim());
}
Copy the code
3.2, the StringBuilder/StringBuffer
In the process of program development, we often encounter String concatenation, convenient and direct way is through the “+” symbol to achieve the purpose, but this way to achieve the efficiency is relatively low, and each execution will create a String object, that is time consuming, and waste space. This problem can be avoided by using the StringBuilder class, which creates a StringBuilder object
StringBuffer and StringBuilder both represent mutable strings and have the same functionality.
- StringBuffer: Methods in StringBuffer use the synchronized modifier to ensure thread-safety but low performance
- StringBuilder: Methods in StringBuilder do not use the synchronized modifier, which is thread-safe but high performance
The StringBuilder is recommended for development
StringBuilder stringBuilder = new StringBuilder("123");// Initialize
Copy the code
3.2.1. String Stitching
Syntax format
append(String str)/append(Char c)
Copy the code
demonstration
StringBuilder stringBuilder = new StringBuilder("123");
System.out.println(stringBuilder.append("abc").append("123"));
Copy the code
advantage
You can call it chained, concatenating it indefinitely
3.2.2, replace,
Syntax format
SetCharAt (int I, char C) : sets the i-th unit of code to character CCopy the code
demonstration
StringBuilder sb = new StringBuilder("123");
sb.setCharAt(1.'A');
System.out.println(sb);
Copy the code
Pay attention to
The first argument is the position to be replaced, and the second argument is the character to be replaced, just char
3.2.3, insert,
Syntax format
Insert (int offset, String STR)/insert(int offset, Char C) : insert a String before the specified positionCopy the code
demonstration
StringBuilder sb = new StringBuilder("123");
sb.insert(1."1234");
System.out.println(sb);
Copy the code
Pay attention to
In the add method, you can add characters or strings
3.2.4, delete,
Syntax format
Delete (int startIndex,int endIndex) : deletes the string between the start position (inclusive) and the end position (exclusive)Copy the code
demonstration
System.out.println(sb.delete(3.6));
Copy the code
Pay attention to
The delete method also contains headers and no tails
4. Common classes
4.1, Math
The Math class contains methods for performing mathematical operations, such as primitives, exponents, logarithms, square roots, trigonometric functions, etc. The methods of this class are static and can be used for processing Math in development
public class MathDemo {
public static void main(String[] args) {
System.out.println(Math.max(99.10));// Return the maximum value
System.out.println(Math.min(99.10));// Return the minimum value
// return a random decimal between [0,1)
double num = Math.random();
System.out.println(num);
// get a random integer between 0,100
int intNum1 = (int) (num * 100);
System.out.println(intNum1);
// The random number between 23 and 104 is equivalent to the random number between 0 and 81 +23
int intNum2 = (int)(Math.random() * 81 + 23); System.out.println(intNum2); }}Copy the code
4.2, the Random
The Random class is used to produce a pseudorandom number (the same Random number is generated from the same seed), and this is how the Random method of the Math class is used at the bottom
public class RandomDemo {
public static void main(String[] args) {
Random r = new Random();
int intNum1 = r.nextInt(100);// Random number within 100
System.out.println(intNum1);
// Randomly obtain A string of 5 letters between A and Z
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
int intNum2 = 65 + r.nextInt(25);
char ch = (char) intNum2; sb.append(ch); } System.out.println(sb); }}Copy the code
4.3, UUID
The Universally Unique Identifier (UUID) is an algorithm based on the computer’s network card, local time, random numbers, etc. Its advantage is that it is truly Unique, but its disadvantage is that the string is too long
public class UUIDDemo {
public static void main(String[] args) {
//UUID A random character string
String uuid = UUID.randomUUID().toString();
System.out.println(uuid);
// Obtain the first five letters of the UUID as the verification code
String code = uuid.substring(0.5);
System.out.println(code);
System.out.println(code.toUpperCase());// Change the captcha to uppercase letters}}Copy the code
4.4. Date classes
4.4.1, the Date class
The Date class represents a specific moment in time and can be interpreted as year, month, day, hour, minute, and second values
A large number of methods in the Date class are marked as already, which is officially not recommended. In development, we use the Date class to represent either the Date (year, month, day) or time (hour, minute, second) types
public class DateDemo {
public static void main(String[] args) {
java.util.Date d = new java.util.Date();
System.out.println(d);// The time style of Europeans and Americans
System.out.println(d.toLocaleString());// Local region time style, obsolete method
long time = d.getTime();// Get the number of milliseconds since 00:00:00, January 1, 1970System.out.println(time); }}Copy the code
4.4.2, SimpleDateFormat
SimpleDateFormat (SimpleDateFormat, SimpleDateFormat, SimpleDateFormat, SimpleDateFormat, SimpleDateFormat, SimpleDateFormat, SimpleDateFormat, SimpleDateFormat, SimpleDateFormat
- Format: Converts the Date type to a String type
- Parse: Converts String to Date
Both formatting and parsing require formatting dates and times
For example:
Yyyy-mm-dd: 2020-12-12 HH: MM: SS 20:12:12 YYYY-MM-DD HH: MM: SS 2020-12-12 20:12:12 YYYY /MM/ DD HH: MM :ss 2020/12/12 20: 12:12 YYYY Yyyy MM month DD day HH MM minute SS second For example, on December 12, 2020 at 20:12 minutes and 12 secondsCopy the code
Formatting and parsing demonstrations:
package day11_CommonUtils2.test.Math;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
/ * * *@author Xiao_Lin
* @version 1.0
* @date2020/12/11 15:21 * /
public class TestMath {
public static void main(String[] args) throws ParseException {
/* Format */
// Create a date class
Date date = new Date();
// Set a format
String paaaern = "yyyy-MM-dd HH:mm:ss";
// Pass the formatting to simpleDateFormat
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(paaaern);
//simpleDateFormat formats the day passed in
String format = simpleDateFormat.format(date);
// Outputs formatting information
System.out.println(format);
/ * * /
// Pass the string information to the simpleDateformat.parse method for parsing and return a Date object
Date d = simpleDateFormat.parse("The 2020-12-11 16:53:48"); ,// Output Date informationSystem.out.println(d); }}Copy the code
4.4.3, Calendar,
Calendar is a Calendar class, which is mainly used to add and subtract the dates and reset the date function. Calendar itself is an abstraction, which must be obtained through the getInstance method
public class CalendarDemo1 {
public static void main(String[] args) throws Exception {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH) + 1;
int date = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
System.out.println(year);/ / 2018
System.out.println(month);/ / 5
System.out.println(date);/ / 17
System.out.println(hour);/ / 15
System.out.println(minute);/ / 1
System.out.println(second);/ / 38
c.add(Calendar.YEAR, 100);// Add 100 to the current year
System.out.println(c.get(Calendar.YEAR));/ / 2118}}Copy the code
4.5. Regular expressions
Regular expressions, short for regex and RE.
Regular expressions are used to determine whether a string conforms to a correct rule. They are usually used to determine operations, replace operations, and split operations in development.
Common rules are as follows:
public class REDemo {
public static void main(String[] args) throws Exception {
// Check if the preceding string is a number, with "\\d" indicating a number
System.out.println("12345678S".matches("\\d"));// false
// Check if the preceding string is a number, with "\\d" indicating a number
System.out.println("12345678".matches("\\d"));// false
// Check if the preceding string is a string of numbers, with "\\d*" indicating multiple numbers
System.out.println("12345678".matches("\\d*"));// true
// Check whether the preceding string of numbers occurs 5-10 times.
System.out.println("1234".matches("\ \ d {5, 10}"));// false
System.out.println("12345678".matches("\ \ d {5, 10}"));// true
// Check if a string is a mobile phone number. The first digit is 1, the second digit is 3/4/5/7/8, and the second digit is 0-9
String regex1 = "^ 1 [3 4 5 7 | | | | 8] [0-9] {9} $";
System.out.println("12712345678".matches(regex1));// false
System.out.println("13712345678".matches(regex1));// true
// Check if a string is an 18-digit ID number. The number appears 17 times and the last digit is 0-9 or X
String regex2 = "\\d{17}[[0-9]X]";
System.out.println("511123200110101234".matches(regex2));// true
System.out.println("51112320011010123X".matches(regex2));// true
System.out.println("51112320011010123S".matches(regex2));// false
// Determines whether a string is 6 to 16 characters, and the first character must be a letter
String regex3 = "^ \ \ w [a zA - Z] {5, 15} $";
System.out.println("will".matches(regex3));// false
System.out.println("17will".matches(regex3));// false
System.out.println("will17willwillwill".matches(regex3));// false
System.out.println("will17".matches(regex3));// true}}Copy the code
5. Array advanced
5.1 bubble sorting method
Compare the size relationship of two adjacent elements from beginning to end. If the former element is larger than the latter, the position will be changed. The maximum value can be obtained after the first round of comparison, and the second largest value will appear after the second round of comparison
The first round of comparison: 5 times of comparison are required, and the maximum value appears after comparison. The second round of comparison: 4 times of comparison are required, and the second largest value appears after comparison. The third round of comparison: three times of comparison are required, and the third largest value appears after comparison. . It can be seen that if there are N elements, n-1 round of comparison is required, and n-m round of comparison is required. I (Number of rounds) Rule for the number of rounds 0 3 Array length - I-1 1 2 Array length -i-1 2 1 Array length -i-1Copy the code
package ArraysAdvanced;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
/ * * *@author Xiao_Lin
* @version 1.0
* @date2020/12/14 14:04 * /
public class Bubble {
public static void main(String[] args) {
int[] nums = new int[10];// Create an array
for (int i = 0; i < nums.length; i++) {
nums[i] = new Random().nextInt(100);// Assign random values to arrays,
}
System.out.println(Arrays.toString(nums));// Print the original array (before sorting)
for (int i = 0 ; i < nums.length-1 ; i++){// Define a control loop to control how many bubbles are required: array length -1
for (int j = 0 ; j < nums.length-1-i ; j++){// Control the number of comparisons per round
int temp = 0;// Set temporary variables for pairwise swapping
if (nums[j]>nums[j+1]) {// If the previous value is greater than the subsequent value, the swap is performed to ensure that the latter value is greater than the previous value
temp = nums[j];// Store large values in temporary variables
nums[j] = nums[j+1];// Assign a small value to a large value
nums[j+1] = temp;// Assign the value of the temporary variable to the small value, thus completing the pairwise swap
}
}
}
System.out.println(Arrays.toString(nums));// Outputs the sorted array}}Copy the code
5.2. Select sort
Start at the current position and find the next smaller value to swap with that position
Implementation idea:(1), control the selection of several rounds: array length -1 (2), control each round from the current position of the number of times to compare I (rounds) number of times to compare each round 0 3 array length - I-1 1 2 array length - I-1 2 1 array length -i-1Copy the code
package com.test;
import java.util.Arrays;
import java.util.Random;
/ * * *@author Xiao_Lin
* @date2020/12/25 forasmuch * /
public class SelectSort {
public static void main(String[] args) {
// Define an array
int[] arr = {7.6.5.4.3};
System.out.println("Before sorting:" + Arrays.toString(arr));
// Define a control loop for several rounds
for (int x = 0; x < arr.length; x++) {
// Define a loop to compare the following elements several times per round, always comparing the current position with the following elements, traversing the following elements
// i=0 j=1 2 3
// i=1 j=2 3
// i=2 j=3
for (int i = x+1; i < arr.length; i++) {
// Compare the current position with the specified element, and swap positions for smaller ones
if (arr[x] > arr[i]) {
int temp = arr[x];
arr[x] = arr[i];
arr[i] = temp;
}
}
}
System.out.println("After sorting:"+ Arrays.toString(arr)); }}Copy the code
5.3. Binary search method
Syntax for finding array elements:
- Linear search: search from beginning to end, poor performance
- Binary search method (split half search) : the premise is that the array elements must be ordered, better performance
package day012_ArraysAdvanced.classing;
/ * * *@author Xiao_Lin
* @version 1.0
* @date 2020/12/14 18:39
*/
public class Find {
/** * binary search method *@paramNums Is the array in which the element is to be found@paramValue Specifies the element to be searched@return* /
public static int binarySearch(int[] nums , int value){// Define a binary search method
int low = 0;// Define the lowest position, default is 0
int hight = nums.length-1;// Define the highest position. Default is the last digit of the array
int mid , midValue; // Define intermediate variable values and ordinals
while (low <= hight){// If the lowest bit is less than or equal to the highest bit, the element we are looking for is still in the number organization, otherwise the element is not in the array, return -1
mid = (low+hight)/2;// Calculate the middle bit
midValue = nums[mid];// Get the middle value
if (value > midValue){// If the variable is to the right of the median value
low = mid+1;// Move the minimum to the last position in the middle
}else if(value < midValue){// If the variable to look for is to the left of the median value
hight = mid-1;// Move the maximum to the first part of the middle position
}else if(value == midValue){// If the intermediate value is equal to the desired value, it is found
return mid;// return the sequence number found}}return -1;// Return -1 to indicate that it cannot be found
}
public static void main(String[] args) {
int[] nums = {1.2.3.4.5.6};
System.out.println(binarySearch(nums, 30)); }}Copy the code
Apis for manipulating Arrays
5.3.1. Print array elements
public class Test01ToString {
public static void main(String[] args) {
int[] arr = new int[] { 10.20.30.40.50.60.70}; String str = Arrays.toString(arr); System.out.println(str); }}Copy the code
5.3.2 Copying array elements
Arrays provides methods for array copying. CopyOf (int[] Original, int newLength) copies the specified array, intercepts it or fills it with zeros. It creates a new array directly. The System class provides a method for copying array elements, and supports copying arrays of any type, not just ints.
package day012_ArraysAdvanced.classing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
/ * * *@author Xiao_Lin
* @version 1.0
* @date2020/12/14 tightly with * /
public class ArraysTestDemo {
public static void main(String[] args) {
// The copyOf method of Arrays
int[] nums = {21.3.4.652.2};
int[] ints = Arrays.copyOf(nums, 10);// We specify that the length of the copied array is 10, which means that it is filled with 0
System.out.println(Arrays.toString(ints));
int[] copyOf = Arrays.copyOf(nums, 3);// We specify the length of the copied array to be 3, which is smaller than the original array
System.out.println(Arrays.toString(copyOf));
/ / System
int[] num = {1.3.5.7.9};
int[] newnum = new int[10];
Where does the source array to be copied start? Where does the source array to be copied start? How long does the value fill in the original array
System.arraycopy(num,0,newnum,0,num.length);
System.out.println(Arrays.toString(newnum));
}
Copy the code
5.3.3 Sorting array elements
The Arrays class already provides the sort method for sorting Arrays, which is optimized and has excellent performance. In development, we just need to call this method directly. Sotr is in ascending order by default, and we can specify the sort method (descending or ascending) later.
import java.util.Arrays;
public class Test03Sort{
public static void main(String[] args) {
int[] arr = new int[] { 2.9.6.7.4.1 };
System.out.println(Arrays.toString(arr));/ / before ordering
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));/ / sorted}}}Copy the code
5.3.4 Binary lookup of arrays
import java.util.Arrays;
public class Test04Search{
public static void main(String[] args) {
int[] arr = new int[] { 1.2.3.4.5.6.7.8.9.10 };
int index = Arrays.binarySearch(arr, 8); System.out.println(index); }}Copy the code
5.4 Add, delete, change and check the array
5.4.1 Array initialization
package day012_ArraysAdvanced.classing.ArraysCRUD;
/ * * *@author Xiao_Lin
* @version 1.0
* @date2020/12/14 michal * /
public class ArraysUtils {
private Integer[] nums = null; // Declare an array
private int size;// Declare the number of elements in the array, not the length
public ArraysUtils(int capacity){// constructor, used for initialization
if (capacity < 0) {// If the passed capacity value is <0, the capacity value is invalid
System.out.println("The size of an array cannot be less than zero.");
return;
}else {
this.nums = new Integer[capacity];// Initializes a new array with the capacity value passed in}}public ArraysUtils(a){// No parameter constructor
this(10);// Call the parameter constructor and pass in an initialized value
}
public Integer[] getNums() {
return nums;
}
public void setNums(Integer[] nums) {
this.nums = nums;
}
public int getSize(a) {
return size;
}
public void setSize(int size) {
this.size = size; }}Copy the code
The test class:
package day012_ArraysAdvanced.classing.ArraysCRUD;
/ * * *@author Xiao_Lin
* @version 1.0
* @date 2020/12/14 19:24
*/
public class TestArraysUtils {
public static void main(String[] args) {
ArraysUtils arraysUtils = new ArraysUtils(13); System.out.println(arraysUtils.getNums().length); }}Copy the code
5.4.2 Array modification
public ArraysUtils set(int num,int index){// Define a method that modifies the element at the specified location and returns ArraysUtils to facilitate write chain calls
if (index < 0){
System.out.println("Index cannot be less than 0");
return null;
}if (index >= size){
System.out.println("Index out of bounds");
return null;
}
nums[index] = num;// Assign the value to be modified to the original value in the table below the specified element
return this;// Returns the current object to facilitate chain calls
}
Copy the code
5.4.3 Search for the specified index of an array
public Integer get(int index){// define a method to query against the specified sequence
if (index < 0){
System.out.println("Index cannot be less than 0");
return null;
}if (index >= size){
System.out.println("Index out of bounds");
return null;
}
return this.nums[index];// Returns the value of the specified sequence
}
Copy the code
5.4.4 Array printing
public String toString(a){// Define a print method
StringBuilder sb = new StringBuilder();Define a StringBuilder object
if (nums == null) {// If the current array is empty
return null;// Return null
}if (size == 0) {// If the current array length is 0
return "[]";// Returns an empty array of characters
}else {
sb.append("[");// Append a "[" to StringBuilder
for (int i = 0; i < size; i++) {// Iterate through the nums array, remembering that I is less than the number of elements in the array, not the length
if (i == size-1) {// If the element to be iterated over is the last element in the array
sb.append(nums[i]).append("]");// Append "]" to the end
}else {
sb.append(nums[i]).append(",");// Otherwise just append elements and,}}}return sb.toString();
}
Copy the code
5.4.5 Append arrays
public ArraysUtils append(int num){
this.nums[size] = num;// Appends the passed value to the last bit of the array
size++;// Add one element to the array
return this;// Return the current object to facilitate chain calls
}
Copy the code
5.4.5 Array expansion
Because the length of the array is fixed, the NUMS array can only store an initialized number of elements. If one more element is stored, an error is reported: the array index is out of bounds. Consider expanding the array at save time. The principle of capacity expansion is as follows:
- Create a new array twice the length of the original array
- Copy all the elements in the old array into the new array
- Assigns a reference to the new array to the old array variable
public ArraysUtils append(int num){
if (size == nums.length){// If the number of elements in the array is equal to the length of the array, it needs to be expanded
this.nums = Arrays.copyOf(nums,nums.length*2+2);// Assign the new array generated by copyOf to the original array and increase its length by 2 +2 elements
}
this.nums[size] = num;
size++;
return this;
}
Copy the code
5.4.6 Array deletion
public ArraysUtils delete(int index){// Define the delete method
if (index < 0) {// if subscript is less than 0
System.out.println("Index cannot be less than 0");
return null;/ / return empty
}if (index >= size){// If the subscript value is larger than the element in the array
System.out.println("Index out of bounds");// Return array out of bounds
return null;
}
for (int i = index ; i < size-1; i++){// Iterate over the elements in the array
nums[i] = nums[i+1];// Assign the last value of the index to be dropped to the first value
}
nums[size-1] = null;// Empty the last position of the array
size--;// The number of elements in the array is reduced by one
return this;Return the current object
}
Copy the code
Six, generics
6.1. Overview of generics
A generic type is a type of data, mainly used when the data type in a class or interface is uncertain. You can use an identifier or placeholder to mark the unknown data type, and then specify the real type of the location type when using the class or interface
Generics can be used in interfaces, classes, and methods, passing data types as parameters, which is more like a template for data types.
If we don’t use generics, we need to cast elements from the container because we don’t know the type
6.2. Customize and use generics
Define a generic
We can use an identifier such as T (Type) to represent an unknown data Type in a class
// Declare the use of the symbol T on the class to represent unknown types
public class Point<T> {
private T x;
private T y;
/ / omit getter/setter
}
Copy the code
Use generic
When creating an Object, a specific type is assigned to an unknown type. When no generic type is specified, the default type is Object.
// No generics are used. The default type is Object
Point p1 = new Point();
Object x1 = p1.getX();
// Use String as the generic type
Point<String> p2 = new Point<String>();
String x2 = p2.getX();
// Use Integer as the generic type
Point<Integer> p3 = new Point<Integer>();
Integer x3 = p3.getX();
Copy the code
6.2. Use generics in collections
class ArrayList<E>{
public boolean add(E e){}public E get(int index){}}Copy the code
We know that this is just an Element, but we don’t know what type it is. E stands for the type of Element, so when we use a container and give it a generic type, it means that the container can only store certain types of data.
// Only String collections can be stored
List<String> list1 = new ArrayList<String>();
list1.add("A");
list1.add("B");
// Only collections of type Integer can be stored
List<Integer> list2 = new ArrayList<Integer>();
list2.add(11);
list2.add(22);
Copy the code
Since the first and last types of collections must be the same, after JDK1.8 you can omit the writing of generics when instantiating objects
List<String> list1 = new ArrayList<String>();
// Can be abbreviated as
List<String> list1 = new ArrayList<>();
Copy the code
Pay attention to
- Generics must be reference types, not primitive data types
List<int> list = new ArrayList<int> ();// Error compiling
Copy the code
- Generics have no inheritance relationship
List<Object> list = new ArrayList<String>(); // Error compiling
Copy the code
Method, which passes the data type as a parameter, is more like a template for the data type.
If we don’t use generics, we need to cast elements from the container because we don’t know the type