Basic introduction and use of common APIs, regular expressions, generic types and Collection APIs

Posted by DuFF on Thu, 30 Dec 2021 09:47:24 +0100

[common API, regular expression, generic, Collection API]

Copy, paste, reprint and delete the infringing contact

primary coverage

  • Date class
    • Java is an object-oriented idea. It will use a class to represent a thing.
    • Date represents the current date object of the system! Month, day, hour, minute and second.
  • DateFormat class
    • Date formatting class, that the date object to get the time is not good-looking!
    • The date formatting class can format the time into our favorite format.
    • Date formatting class can parse string time into Date object!! “2019-10-01 09:28:00”
  • Calendar Class
    • The calendar class represents the calendar object corresponding to the current date object. Calendar information is more abundant.
  • System class
    • Represents the operating system object corresponding to the current JVM virtual machine.
    • You can take the system time.
    • You can let the program exit the JVM virtual machine and let the program die immediately!!
    • You can make array copies.
  • StringBuilder class
    • String class is not suitable for string splicing, addition, deletion and other operations. Immutable string, poor addition and deletion performance!
    • StringBuilder is very suitable for adding, deleting, modifying and querying strings, with better performance!!
  • Packaging
    • Everything is an object.
    • int Integer int age = 21; Integer age1 = 21;
    • float Float
    • double Double
  • generic paradigm
    • ArrayLIst lists = new ArrayList<>();
  • Collection: list, map, set
    • Three day collection framework (key content, necessary for development!!)

Teaching objectives

  • You can use the date class to output the current date

    • Date d = new Date();
    • System.out.println(d);
  • You can use methods that format dates as strings

    • SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    • String rs = sdf.format("Date object")
    • String rs = sdf.format("time millisecond value")
  • You can use the method of converting a string to a date

    • SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    • String str = "2019-11-11 11:11:11";
    • Data d = sdf.parse(str );
    • System.out.println(d);
  • The array copy method of the System class can be used

    // 3. Array copy:
    int[] arrs1 = {10 , 20 , 30 , 40 , 50 , 60 , 70 , 80};
    // arrs2 = [ 0 , 0 , 0 , 0 , 0 , 0]
    // arrs2 = [0 , 0 , 30 , 40 , 50 , 0]
    // I want to assign 30, 40 and 50 of the first array to the second array!
    int[] arrs2 = new int[6];
    
    /**
     arraycopy(Object src,  int  srcPos,
     Object dest, int destPos,
     int length)
     Parameter 1: original array.
     Parameter 2: where does the original array copy from
     Parameter 3: target array
     Parameter 4: where to copy to the target array.
     Parameter 5: how many copies!
     */
    System.arraycopy(arrs1, 2 ,arrs2 , 2 , 3);
    System.out.println(Arrays.toString(arrs2));
    
  • The System class can be used to obtain the current millisecond time value

    • ```java
      long time = System.currentTimeMillis();
  • Be able to say the problems that can be solved by using the StringBuilder class

    • Can do string operations (splicing, addition, deletion, inversion)
  • Be able to use StringBuilder for string splicing

    • append
  • Be able to name the packaging class corresponding to 8 basic types

    • int Integer

    • char Character

    • ```properties
      Basic data type wrapper class
      byte Byte
      short Short
      Int integer (special)
      long Long
      float Float
      double Double
      Character (special)
      boolean Boolean

  • Be able to speak the concept of automatic packing and unpacking

    • ```properties
      Automatic packing: you can directly assign variables or values of basic data types to corresponding packing objects.
      Automatic unpacking: you can assign the object of packing class to the variable of basic data type.
  • The string can be converted to the corresponding basic type

    Function 3: Convert the number of string type into the value of corresponding basic data type!! (really useful and important)
              Xxxx.parseXxxx("Number of string type")
              Xxxx.valueOf("Number of string type"): Recommended!
    
  • The basic type can be converted to the corresponding string

    // Function 2: the wrapper class can convert the value of the basic data type into a string.
    // 1. Convert the value of basic data type into string: toString()
    Integer num = 23 ;
    String numStr1 = num.toString();
    System.out.println(numStr1+1); // 231
    
    // 2. Convert the value of basic data type into string:
    Integer num1 = 23 ;
    String num1Str1 = Integer.toString(num1);
    System.out.println(num1Str1+1); // 231
    
    // 3. Convert the value of basic data type to string:
    Integer num2 = 23 ;
    String num2Str1 = num2 + "" ; //Common practices!
    System.out.println(num2Str1+1); // 231
    
  • Be able to describe the common functions of the Collection

    • ```properties
      Collection is the root class of a collection. Its function is that all collections can be used directly.
      • Public Boolean add (E): adds the given object to the current collection.
      • public void clear(): clear all elements in the collection.
      • Public Boolean remove (E): deletes the given object from the current collection.
      • public boolean contains(Object obj): determines whether the current collection contains a given object.
      • public boolean isEmpty(): judge whether the current collection is empty.
      • public int size(): returns the number of elements in the collection.
      • public Object[] toArray(): store the elements in the collection into an array
  • Ability to create collection objects using generics

    • ```java
      ArrayList lists = new ArrayList<>(); // JDK 1.7 after the simplified writing of generic!
      ArrayList lists1 = new ArrayList<>();// JDK 1.7 after the simplified writing of generic!
  • Be able to understand the upper and lower bounds of generics

    • ? extends Car : ? Must be a subclass of car or itself. upper limit
    • ? super Car : ? Must be a parent of car or itself. The lower limit is not used!!
  • Be able to explain the role of generic wildcards

    • ? You can receive all types on behalf when using generics

Chapter 1 DateFormat class

java.text.DateFormat is an abstract class of date / time formatting subclass. Through this class, we can help us complete the conversion between date and text, that is, we can convert back and forth between Date object and String object.

  • Format: converts a Date object into a String object according to the specified format.
  • Parsing: converts a String object into a Date object in the specified format.

1.1 construction method

Because DateFormat is an abstract class and cannot be used directly, it needs a common subclass Java text. SimpleDateFormat. This class needs a pattern (format) to specify the standard for formatting or parsing. The construction method is:

  • public SimpleDateFormat(String pattern): construct SimpleDateFormat with the date format symbols of the given schema and default locale. The parameter pattern is a string representing the custom format of date and time.

1.2 Format Rules

Common format rules are:

Identification letters (case sensitive)meaning
yyear
Mmonth
dday
HTime
mbranch
ssecond

Note: for more detailed format rules, please refer to the API documentation of SimpleDateFormat class.

1.3 common methods

Common methods of DateFormat class are:

  • public String format(Date date): formats the Date object as a string.

  • public Date parse(String source): parses a string into a Date object.

    public class SimpleDateFormatDemo {
        public static void main(String[] args) throws ParseException {
            //Format: from Date to String
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
            String s = sdf.format(d);
            System.out.println(s);
            System.out.println("--------");
    
            //From String to Date
            String ss = "2048-08-09 11:11:11";
            //ParseException
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dd = sdf2.parse(ss);
            System.out.println(dd);
        }
    }
    

Summary: DateFormat can convert Date object and string to each other.

Chapter II Calendar Class

2.1 general

  • java. util. The calendar class represents a "Calendar Class" that can perform date operations. It is an abstract class and cannot create objects. We can use its subclass: Java util. Gregoriancalendar class.
  • There are two ways to get GregorianCalendar objects:
    • Create GregorianCalendar objects directly;
    • Get GregorianCalendar object through Calendar's static method getInstance() [used in this lesson]

2.2 common methods

Method nameexplain
public static Calendar getInstance()Gets a GregorianCalendar object of its subclass.
public int get(int field)Gets the value of a field. The field parameter indicates which field value to obtain,
You can use constants defined in Calender to represent:
Calendar.YEAR: year
Calendar.MONTH: month
Calendar.DAY_OF_MONTH: the date of the month
Calendar.HOUR: hour
Calendar.MINUTE: minutes
Calendar.SECOND: Second
Calendar.DAY_OF_WEEK: Week
public void set(int field,int value)Set the value of a field
public void add(int field,int amount)Increase / decrease the specified value for a field

2.3 get method example

public class Demo {
    public static void main(String[] args) {
        //1. Get a GregorianCalendar object
        Calendar instance = Calendar.getInstance();//Get subclass object

        //2. Print subclass objects
        System.out.println(instance);

        //3. Get properties
        int year = instance.get(Calendar.YEAR);
        int month = instance.get(Calendar.MONTH) + 1;//The month value of Calendar is 0-11
        int day = instance.get(Calendar.DAY_OF_MONTH);

        int hour = instance.get(Calendar.HOUR);
        int minute = instance.get(Calendar.MINUTE);
        int second = instance.get(Calendar.SECOND);

        int week = instance.get(Calendar.DAY_OF_WEEK);//Return value range: 1 -- 7, respectively: "Sunday", "Monday", "Tuesday", "Saturday"

        System.out.println(year + "year" + month + "month" + day + "day" + 
                           	hour + ":" + minute + ":" + second);
        System.out.println(getWeek(week));

    }

    //Look up table method, query the day of the week
    public static String getWeek(int w) {//w = 1 --- 7
        //Make a table (array)
        String[] weekArray = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        //            Index [0] [1] [2] [3] [4] [5] [6]
        //Look up table
        return weekArray[w - 1];
    }
}

2.4 set method example:

public class Demo {
    public static void main(String[] args) {
        //Set attribute - set(int field,int value):
		Calendar c1 = Calendar.getInstance();//Get current date

		//Calculate the day of the week on which the monitor was born (if the monitor's birth date is March 18, 1998)
		c1.set(Calendar.YEAR, 1998);
		c1.set(Calendar.MONTH, 3 - 1);//Convert to Calendar internal month value
		c1.set(Calendar.DAY_OF_MONTH, 18);

		int w = c1.get(Calendar.DAY_OF_WEEK);
		System.out.println("The monitor was born on:" + getWeek(w));

        
    }
    //Look up table method, query the day of the week
    public static String getWeek(int w) {//w = 1 --- 7
        //Make a table (array)
        String[] weekArray = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        //            Index [0] [1] [2] [3] [4] [5] [6]
        //Look up table
        return weekArray[w - 1];
    }
}

2.5 example of add method:

public class Demo {
    public static void main(String[] args) {
        //Calculate the year, month, day and day after 200 days?
		Calendar c2 = Calendar.getInstance();//Get current date
        c2.add(Calendar.DAY_OF_MONTH, 200);//Date plus 200

        int y = c2.get(Calendar.YEAR);
        int m = c2.get(Calendar.MONTH) + 1;//Convert to actual month
        int d = c2.get(Calendar.DAY_OF_MONTH);

        int wk = c2.get(Calendar.DAY_OF_WEEK);
        System.out.println("200 Days later:" + y + "year" + m + "month" + d + "day" + getWeek(wk));

    }
    //Look up table method, query the day of the week
    public static String getWeek(int w) {//w = 1 --- 7
        //Make a table (array)
        String[] weekArray = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        //            Index [0] [1] [2] [3] [4] [5] [6]
        //Look up table
        return weekArray[w - 1];
    }
}

Chapter 3 Math class

3.1 general

  • java. Lang. math (class): Math contains methods that perform basic numeric operations.
  • It cannot create objects. Its construction method is "private". Because it is internally a "static method", it can be called directly through the "class name".

3.2 common methods

Method nameexplain
public static int abs(int a)Get the absolute value of parameter a:
public static double ceil(double a)Round up
public static double floor(double a)Round down
public static double pow(double a, double b)Get the power of a to the b
public static long round(double a)Rounding

3.3 example code

public class Demo {
    public static void main(String[] args) {
        System.out.println("-5 Absolute value of:" + Math.abs(-5));//5
    	System.out.println("3.4 Round up:" + Math.ceil(3.4));//4.0
    	System.out.println("3.4 Round down:" + Math.floor(3.4));//3.0
    	System.out.println("2 To the 8th power of:" + Math.pow(2, 8));//256.0
    	System.out.println("3.2 rounding:" + Math.round(3.2));//3
    	System.out.println("3.5 rounding:" + Math.round(3.5));//4

    }
}

Chapter IV System

4.1 General

java.lang.System class provides a large number of static methods to obtain system related information or system level operations.

4.2 common methods

Method nameexplain
public static void exit(int status)Terminate the currently running Java virtual machine. Non zero indicates abnormal termination
public static long currentTimeMillis()Returns the current time in milliseconds

4.3 practice

Output 1-10000 on the console and calculate how many milliseconds this code has been executed

import java.util.Date;
//The time (in milliseconds) it takes to verify that the for loop prints numbers 1-9999
public class SystemDemo {
    public static void main(String[] args) {
       	//Gets the current time in milliseconds
       System.out.println(System.currentTimeMillis()); 
      //Calculate program run time
       long start = System.currentTimeMillis();
        for (int i = 1; i <= 10000; i++) {
            System.out.println(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("Total time taken MS:" + (end - start));
    }  
}

Chapter V BigDecimal class

5.1 introduction

Floating point number operation accuracy;

Look at the program and say the result:

public static void main(String[] args) {
    System.out.println(0.09 + 0.01);
    System.out.println(1.0 - 0.32);
    System.out.println(1.015 * 100);
    System.out.println(1.301 / 100);
}

5.2 general

Related contentSpecific description
packagejava. When using math, you need to guide the package
Class declarationpublic class BigDecimal extends Number implements Comparable
describeThe BigDecimal class provides operations for arithmetic, scaling, rounding, comparison, hashing, and format conversion. It provides a more accurate data calculation method

5.3 construction method

Construction method namedescribe
BigDecimal(double val)Encapsulate data of type double as a BigDecimal object
BigDecimal(String val)Converts the string representation of BigDecimal to BigDecimal

Note: the second method is recommended. The first method has accuracy problems;

5.4 common methods

The most used method in BigDecimal class is the method provided to perform four operations, as follows:

Method declarationdescribe
public BigDecimal add(BigDecimal value)Addition operation
public BigDecimal subtract(BigDecimal value)Subtraction operation
public BigDecimal multiply(BigDecimal value)Multiplication
public BigDecimal divide(BigDecimal value)Trigger operation

Note: for the divide method, if the division is not complete, Java. Net will appear Lang.arithmeticexception exception. At this point, you can use another overloaded method of the divide method;

BigDecimal divide(BigDecimal divisor, int scale, int roundingMode): divisor: BigDecimal object corresponding to divisor; Scale: exact number of digits; roundingMode

Summary: decimal operation in Java may have precision problems. If you want to solve this precision problem, you can use BigDecimal

Chapter 6 regular expressions

6.1 concept and demonstration of regular expression

  • In Java, we often need to verify some strings. For example, the age must be a 2-digit number, the user name must be 8 digits long, and can only contain uppercase and lowercase letters, numbers, etc. Regular expressions are rules used to validate various strings. It internally describes some rules. We can verify whether the string entered by the user matches this rule.
  • Let's take a look at an example without regular expression verification: the following program allows users to enter a QQ number. We want to verify:
    • QQ number must be 5 – 15 digits long
    • And it must be all numbers
    • And the first cannot be 0
public class Demo {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Please enter your QQ Number:");
		String qq = sc.next();
		
		System.out.println(checkQQ(qq));
	}
	//We write our own code to verify the QQ number
	private static boolean checkQQ(String qq) {
		//1. Verify 5-15 bits
		if(qq.length() < 5 || qq.length() > 15){
			return false;
		}
		//2. All must be numbers;
		for(int i = 0;i < qq.length() ; i++){
			char c = qq.charAt(i);
			if(c < '0' || c > '9'){
				return false;
			}
		}
		//3. The first place cannot be 0;
		char c = qq.charAt(0);
		if(c == '0'){
			return false;
		}
		return true;//Verification passed
	}
	
}
  • Use regular expression validation:
public class Demo {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Please enter your QQ Number:");
		String qq = sc.next();
		
		System.out.println(checkQQ2(qq));
	}
	//Using regular expression validation
	private static boolean checkQQ2(String qq){
		String regex = "[1-9]\\d{4,14}";//regular expression 
		return qq.matches(regex);
	}
}

The variable regex of String type in the checkQQ2() method of the above program stores a "regular expression", which describes the three rules we need. The matches() method is a method of the String class. It is used to receive a regular expression and match the "this object" with the parameter "regular expression". If the object conforms to the rules of the regular expression, it returns true, otherwise it returns false.

Let's focus on how to write regular expressions

6.2 regular expressions - character classes

  • Syntax example:
  1. [abc]: represents one of a, b, or c characters.
  2. [^ abc]: represents any character except a,b,c.
  3. [a-z]: one of all lowercase characters representing a-z.
  4. [A-Z]: one of all uppercase characters representing A-Z.
  5. [0-9]: represents a numeric character between 0-9.
  6. [a-zA-Z0-9]: represents any character between A-Z or A-Z or 0-9.
  7. [a-dm-p]: any character from a to d or m to P.
  • Code example:
public class Demo {
	public static void main(String[] args) {
		String str = "ead";
		
		//1. Verify whether str starts with h and ends with d, with a character in a, e, I, O and u in the middle
		String regex = "h[aeiou]d";
		System.out.println("1." + str.matches(regex));
		
		//2. Verify whether str starts with h and ends with d, and the middle is not a character in a, e, I, O and U
		regex = "h[^aeiou]d";
		System.out.println("2." +  str.matches(regex));
		
		//3. Verify that str starts with any lowercase character of a-z followed by ad
		regex = "[a-z]ad";
		System.out.println("3." + str.matches(regex));
		
		//4. Verify that str starts with a character between a-d or m-p, followed by ad
		regex = "[[a-d][m-p]]ad";
		System.out.println("4." + str.matches(regex));
	}
}

6.3 regular expressions - logical operators

  • Syntax example:
    1. &&: and
    2. |: or
  • Code example:
public class Demo {
	public static void main(String[] args) {
		String str = "had";
		
		//1. The string is required to start with a lowercase consonant character followed by ad
		String regex = "[a-z&&[^aeiou]]ad";
		System.out.println("1." + str.matches(regex));
		
		//2. The string is required to start with a character in aeiou followed by ad
		regex = "[a|e|i|o|u]ad";//This is equivalent to: regex = "[aeiou]ad";
		System.out.println("2." + str.matches(regex));
	}
}

6.4 regular expressions - predefined characters

  • Syntax example:
    1. “.” : Matches any character.
    2. "\ d": abbreviation of any number [0-9];
    3. "\ D": abbreviation of any non numeric [^ 0-9];
    4. "\ s": shorthand for white space character: [\ t\n\x0B\f\r] "
    5. "\ s": abbreviation for non whitespace character: [^ \ S] "
    6. "\ w": abbreviation of word character: [a-zA-Z_0-9]
    7. '\ W': non word character: [^ \ w]
  • Code example:
public class Demo {
	public static void main(String[] args) {
		String str = "258";
		
		//1. Verify that str is 3 digits
		String regex = "\\d\\d\\d";
		System.out.println("1." + str.matches(regex));
		
		//2. Verify that the mobile phone number starts with 1, the second digit is 3 / 5 / 8, and the remaining 9 digits are 0-9
        str = "13513153355";//String to validate
		regex = "1[358]\\d\\d\\d\\d\\d\\d\\d\\d\\d";//regular expression 
		System.out.println("2." + str.matches(regex));
		
		//3. Verify that the string starts with h and ends with d, with any characters in the middle
		str = "had";//String to validate
		regex = "h.d";//regular expression 
		System.out.println("3." + str.matches(regex));
		
		//4. Verify whether str is: had
        str = "had.";//String to validate
		regex = "had\\.";//\. For '.' Symbol, because It is predefined as "any character" in regular and cannot be used directly
		System.out.println("4." + str.matches(regex));
		
	}
}

6.5 regular expressions - quantifiers

  • Syntax example:
    1. X? : 0 or 1 times
    2. X *: 0 to more times
    3. X +: 1 or more times
    4. X{n}: exactly n times
    5. X{n,}: at least N times
    6. X{n,m}: n to m times (both N and m are included)
  • Code example:
public class Demo {
	public static void main(String[] args) {
		String str = "";
		
		//1. Verify that str is a three digit number
        str = "012";
		String regex = "\\d{3}";
		System.out.println("1." + str.matches(regex));
		
		//2. Verify that str is a multi digit number
        str = "88932054782342";
		regex = "\\d+";
		System.out.println("2." + str.matches(regex));
		
		//3. Verify whether str is a mobile phone number:
        str = "13813183388";
		regex = "1[358]\\d{9}";
		System.out.println("3." + str.matches(regex));
		
		//4. Verify decimal point: decimal point must appear, but it can only appear once
		String s2 = "3.1";
		regex = "\\d*\\.{1}\\d+";
		System.out.println("4." + s2.matches(regex));
		
		//5. Verify decimal: the decimal point may not appear or may appear once
		regex = "\\d+\\.?\\d+";
		System.out.println("5." + s2.matches(regex));
		
		//6. Verify decimal: matching required: 3, 3 3.14,+3.14,-3.
        s2 = "-3.";
		regex = "[+-]\\d+\\.?\\d*";
		System.out.println("6." + s2.matches(regex));
		
		//7. Verification qq number: 1). 5-15 digits; 2). All numbers; 3). The first digit is not 0
        s2 = "1695827736";
		regex = "[1-9]\\d{4,14}";
		System.out.println("7." + s2.matches(regex));
	}
}

6.6 regular expression - grouping parentheses ()

public class Demo {
	public static void main(String[] args) {
		String str = "DG8FV-B9TKY-FRT9J-99899-XPQ4G";
		
		//Verify the serial number: it is divided into 5 groups separated by - and each group is composed of 5-digit A-Z or 0-9 characters
		String regex = "([A-Z0-9]{5}-){4}[A-Z0-9]{5}";
		System.out.println(str.matches(regex));
	}
}

6.7 using regular expressions in the split method of string

  • Prototype of split() method of String class:

    public String[] split(String regex)//The parameter regex is a regular expression. You can use the symbols in the current string that match the regex regular expression as "separators" to cut the string.
    
  • Code example:

public class Demo {
	public static void main(String[] args) {
		String str = "18  4 567       99     56";
		String[] strArray = str.split(" +");
		for (int i = 0; i < strArray.length; i++) {
			System.out.println(strArray[i]);
		}
	}
}

6.8 using regular expressions in the replaceAll method of string class

  • Prototype of replaceAll() method of String class:
public String replaceAll(String regex,String newStr)//The parameter regex is a regular expression. You can replace the string matching the regex regular expression in the current string with newStr.
  • Code example:
public class Demo {
    public static void main(String[] args) {
        //Replace the "number" in the following string with "*"
        String str = "jfdk432jfdk2jk24354j47jk5l31324";
        System.out.println(str.replaceAll("\\d+", "*"));
    }
}

Chapter VII packaging

7.1 general

Java provides two type systems, basic type and reference type. Using basic types is efficient. However, in many cases, objects will be created for use, because objects can do more functions. If you want our basic types to operate like objects, you can use the wrapper classes corresponding to the basic types, as follows:

Basic typeCorresponding wrapper class (in java.lang package)
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

7.2 Integer class

  • Overview of Integer class

    Wrap the value of the original type int in an object

  • Integer class construction method and static method

Method nameexplain
public Integer(int value)Create Integer object based on int value (obsolete)
public Integer(String s)Create Integer object based on String value (obsolete)
public static Integer valueOf(int i)Returns an Integer instance representing the specified int value
public static Integer valueOf(String s)Returns the Integer object that holds the specified String value
  • Sample code
public class IntegerDemo {
    public static void main(String[] args) {
        //public Integer(int value): creates an Integer object based on the int value (obsolete)
        Integer i1 = new Integer(100);
        System.out.println(i1);

        //public Integer(String s): creates an Integer object based on the String value (obsolete)
        Integer i2 = new Integer("100");
		//Integer i2 = new Integer("abc"); //NumberFormatException
        System.out.println(i2);
        System.out.println("--------");

        //public static Integer valueOf(int i): returns an Integer instance representing the specified int value
        Integer i3 = Integer.valueOf(100);
        System.out.println(i3);

        //public static Integer valueOf(String s): returns the Integer object that holds the specified String value 
        Integer i4 = Integer.valueOf("100");
        System.out.println(i4);
    }
}

7.3 packing and unpacking

The process of back and forth conversion between the basic type and the corresponding packing class object is called "packing" and "unpacking":

  • Boxing: convert from basic type to corresponding wrapper class object.
  • Unpacking: convert from packing class object to corresponding basic type.

Take Integer and int as an example: (just understand the code)

Basic value - > packing object

Integer i = new Integer(4);//Using constructor functions
Integer iii = Integer.valueOf(4);//Use the valueOf method in the wrapper class

Packing object ----- > basic value

int num = i.intValue();

7.4 automatic packing and unpacking

Since we often need to convert between basic types and packaging classes, starting from Java 5 (JDK 1.5), the boxing and unpacking of basic types and packaging classes can be completed automatically. For example:

Integer i = 4;//Automatic packing. Equivalent to integer I = integer valueOf(4);
i = i + 5;//Right of the equal sign: convert the I object to the basic value (automatic unpacking) i.intValue() + 5;
//After the addition operation is completed, box again and convert the basic value into an object.

7.5 conversion between basic type and string

Convert basic type to String

  • Conversion mode
  • Method 1: add an empty string directly after the number
  • Method 2: use the String class static method valueOf()
  • Sample code
public class IntegerDemo {
    public static void main(String[] args) {
        //int --- String
        int number = 100;
        //Mode 1
        String s1 = number + "";
        System.out.println(s1);
        //Mode 2
        //public static String valueOf(int i)
        String s2 = String.valueOf(number);
        System.out.println(s2);
        System.out.println("--------");
    }
}

Convert String to base type

Except for the Character class, all other wrapper classes have parseXxx static methods that can convert string parameters to corresponding basic types:

  • public static byte parseByte(String s): converts a string parameter to the corresponding byte basic type.
  • public static short parseShort(String s): converts a string parameter to the corresponding short basic type.
  • public static int parseInt(String s): converts a string parameter to the corresponding int basic type.
  • public static long parseLong(String s): converts a string parameter to the corresponding long basic type.
  • public static float parseFloat(String s): converts a string parameter to the corresponding float basic type.
  • public static double parseDouble(String s): converts a string parameter to the corresponding double basic type.
  • public static boolean parseBoolean(String s): converts a string parameter to the corresponding boolean basic type.

Code usage (only take the static method parseXxx of Integer class as an example), such as:

  • Conversion mode
    • Method 1: first convert the string number to Integer, and then call the valueOf() method
    • Method 2: convert through Integer static method parseInt()
  • Sample code
public class IntegerDemo {
    public static void main(String[] args) {
        //String --- int
        String s = "100";
        //Method 1: String --- Integer --- int
        Integer i = Integer.valueOf(s);
        //public int intValue()
        int x = i.intValue();
        System.out.println(x);
        //Mode 2
        //public static int parseInt(String s)
        int y = Integer.parseInt(s);
        System.out.println(y);
    }
}

Note: if the content of the string parameter cannot be correctly converted to the corresponding basic type, Java. Java. XML will be thrown Lang.numberformatexception exception.

Chapter 8 generics (difficulties)

8.1 generic overview

When we learned about the collection, we all know that any Object can be stored in the collection. As long as the objects are stored in the collection, they will be promoted to Object type. When we take out each Object and perform corresponding operations, we must use type conversion.

Look at the following code:

public class GenericDemo {
	public static void main(String[] args) {
		Collection coll = new ArrayList();
		coll.add("abc");
		coll.add("itcast");
		coll.add(5);//Because there is no restriction on the collection, any type can be stored in it
		Iterator it = coll.iterator();
		while(it.hasNext()){
			//To print the length of each String, you need to convert the iterated object into String type
			String str = (String) it.next();
			System.out.println(str.length());
		}
	}
}

A problem occurred while the program was running lang.ClassCastException. Why do type conversion exceptions occur? Let's analyze: because any type of element in the Collection can be stored. Causes a runtime ClassCastException to be thrown when fetching. How to solve this problem? Although a Collection can store various objects, in fact, a Collection usually stores only objects of the same type. For example, they are all stored string objects. Therefore, after JDK5, generic syntax is added, so that you can specify classes or methods to support generics when designing the API. In this way, when we use the API, it becomes more concise and gets syntax check at compile time.

  • Generics: unknown types can be used in advance in classes or methods.

tips: generally, when creating an Object, the unknown type is determined as the specific type. When no generic type is specified, the default type is Object type.

8.2 benefits of using generics

The previous section only explained the introduction of generics, so what are the benefits of generics?

  • When the ClassCastException of the runtime is transferred to the compilation time, it becomes a compilation failure.
  • Avoid the trouble of type forced conversion.

Let's experience it through the following code:

public class GenericDemo2 {
	public static void main(String[] args) {
        Collection<String> list = new ArrayList<String>();
        list.add("abc");
        list.add("itcast");
        // list.add(5);// When the collection has an explicit type, an error will be reported if the storage types are inconsistent
        // If the collection has specified the specific element type, the iterator will also know the specific traversal element type when using the iterator
        Iterator<String> it = list.iterator();
        while(it.hasNext()){
            String str = it.next();
            //When you use iterator < String > to control the element type, you don't need to force conversion. The obtained element is directly of String type
            System.out.println(str.length());
        }
	}
}

tips: generics are part of data types. We combine class names and generics as data types.

8.3 definition and use of generics

We will make a lot of use of generics in the collection. Here we can learn about generics completely.

Generics are used to flexibly apply data types to different classes, methods and interfaces. Pass the data type as a parameter.

Define and use classes that contain generics

Define format:

Modifier  class Class name<Variables representing generics> {  }

For example, the ArrayList collection in the API:

Generics are not specific when defined, but become specific when used. Determine the specific data type of the generic when using it.

class ArrayList<E>{ 
    public boolean add(E e){ }

    public E get(int index){ }
   	....
}

Use generics: that is, when generics are determined.

Determine generics when creating objects

For example, ArrayList < string > List = new ArrayList < string > ();

At this time, the value of variable E is of String type, so our type can be understood as:

class ArrayList<String>{ 
     public boolean add(String e){ }

     public String get(int index){  }
     ...
}

For another example, ArrayList < integer > List = new ArrayList < integer > ();

At this time, the value of variable E is Integer type, so our type can be understood as:

class ArrayList<Integer> { 
     public boolean add(Integer e) { }

     public Integer get(int index) {  }
     ...
}

Methods with generics

Define format:

Modifier  <Variables representing generics> Return value type method name(parameter){  }

For example,

public class MyGenericMethod {	  
    public <MVP> void show(MVP mvp) {
    	System.out.println(mvp.getClass());
    }
    
    public <MVP> MVP show2(MVP mvp) {	
    	return mvp;
    }
}

When a method is called, the type of the generic type is determined

public class GenericMethodDemo {
    public static void main(String[] args) {
        // create object
        MyGenericMethod mm = new MyGenericMethod();
        // Presentation method tips
        mm.show("aaa");
        mm.show(123);
        mm.show(12.45);
    }
}

Interface with generics

Define format:

Modifier  interface Interface name<Variables representing generics> {  }

For example,

public interface MyGenericInterface<E>{
	public abstract void add(E e);
	
	public abstract E getE();  
}

Use format:

1. Determine the type of generic when defining a class

for example

public class MyImp1 implements MyGenericInterface<String> {
	@Override
    public void add(String e) {
        // Omit
    }

	@Override
	public String getE() {
		return null;
	}
}

At this point, the value of generic E is of type String.

2. The type of a generic is always uncertain until the type of the generic is determined when the object is created

for example

public class MyImp2<E> implements MyGenericInterface<E> {
	@Override
	public void add(E e) {
       	 // Omit
	}

	@Override
	public E getE() {
		return null;
	}
}

Determine generics:

/*
 * use
 */
public class GenericInterface {
    public static void main(String[] args) {
        MyImp2<String>  my = new MyImp2<String>();  
        my.add("aa");
    }
}

8.4 generic wildcards

When a generic class or interface is used, the generic type in the passed data is uncertain. You can use the wildcard <? > express. However, once the generic wildcard is used, only the common methods in the Object class can be used, and the methods of the elements in the collection cannot be used.

Basic use of wildcards

Generic wildcard: when you don't know what type to use to receive, you can use?,? Indicates an unknown wildcard.

At this time, only data can be accepted, and data cannot be stored in the collection.

For example, you can understand and use it:

public static void main(String[] args) {
    Collection<Intger> list1 = new ArrayList<Integer>();
    getElement(list1);
    Collection<String> list2 = new ArrayList<String>();
    getElement(list2);
}
public static void getElement(Collection<?> coll){}
// ? Representative can receive any type
 Generic type does not have inheritance relationship Collection<Object> list = new ArrayList<String>();This is wrong

Advanced use of wildcards

When you set generics before, you can actually set them arbitrarily, as long as they are classes. However, the upper and lower limits of a generic can be specified in JAVA generics.

Upper limit of generics:

  • Format: type name <? Extensions class > object name
  • Meaning: only this type and its subclasses can be accepted

Lower bound of generics:

  • Format: type name <? Super class > object name
  • Meaning: only this type and its parent type can be accepted

For example, we now know Object class, String class, Number class and Integer class, where Number is the parent class of Integer

public static void main(String[] args) {
    Collection<Integer> list1 = new ArrayList<Integer>();
    Collection<String> list2 = new ArrayList<String>();
    Collection<Number> list3 = new ArrayList<Number>();
    Collection<Object> list4 = new ArrayList<Object>();
    
    getElement(list1);
    getElement(list2);//report errors
    getElement(list3);
    getElement(list4);//report errors
  
    getElement2(list1);//report errors
    getElement2(list2);//report errors
    getElement2(list3);
    getElement2(list4);
  
}
// Upper limit of generics: generics at this time?, Must be of type Number or a subclass of type Number
public static void getElement1(Collection<? extends Number> coll){}
// Lower limit of generics: generics at this time?, Must be of type Number or a parent of type Number
public static void getElement2(Collection<? super Number> coll){}

Chapter IX Collection

9.1 collection overview

In the previous basic class, we have learned and used the collection ArrayList, so what is the collection?

  • Collection: a collection is a container provided in java that can be used to store multiple data.

Since both sets and arrays are containers, what is the difference between them?

  • The length of the array is fixed. The length of the collection is variable.
  • The elements of the same type are stored in the array, and any type of data can be stored. Collections store reference data types. If you want to store basic type data, you need to store the corresponding packaging type.

9.2 inheritance system of collection common classes

Collection: the root interface of a single column collection class. It is used to store a series of elements that conform to certain rules. It has two important sub interfaces, namely Java util. List and Java util. Set. Among them, list is characterized by ordered elements and repeatable elements. Set is characterized by non repeatable elements. The main implementation classes of the list interface are Java util. ArrayList and Java util. The main implementation classes of LinkedList and set interfaces are Java util. HashSet and Java util. LinkedHashSet.

From the above description, it can be seen that JDK provides rich collection class libraries. In order to facilitate beginners to learn systematically, next, a diagram is used to describe the inheritance system of common collection classes

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-H2rIHJqw-1640765014490)(imgs\Collection collection system diagram. jpg)]

Note: this figure is only our common sets. These sets do not mean that there are only these sets.

The Collection itself is a tool, which is stored in Java Util package. The Collection interface defines the most common content in the single column Collection framework.

9.3 common API of collection

Collection is the parent interface of all single column collections. Therefore, some common methods for single column collections (List and Set) are defined in collection, which can be used to operate all single column collections. The method is as follows:

  • Public Boolean add (E): adds the given object to the current collection.
  • public void clear(): clear all elements in the collection.
  • Public Boolean remove (E): deletes the given object from the current collection.
  • public boolean contains(Object obj): determines whether the current collection contains a given object.
  • public boolean isEmpty(): judge whether the current collection is empty.
  • public int size(): returns the number of elements in the collection.
  • public Object[] toArray(): store the elements in the collection into an array

tips: there are more than the above methods in the Collection. Other methods can view the API and learn by themselves.

Topics: Java regex