1. The enumeration class

1.1 What are enumerated Classes?

  • Class has a finite number of objects, deterministic. We call this class an enumerated class;
  • When defining a set of constants, the use of enumerated classes is strongly recommended;
  • If there is only one object in the enumerated class, it can be implemented as a singleton pattern;
  • You cannot inherit from other classes(Because it has been inheritedjava.lang.EnumClass);
  • switchThe parameter can be Enum.
  • Enum Allows writing methods for EUNM instances. So you can assign different behaviors to each enum instance.

1.2 Definition of enumerated classes

//1. The simplest enumerated class
public enum Season {
    //1. Enumerates all the objects in the class, separated by ",",",","; The end of the
    spring,
    SUMMER,
    AUTUMN,
    WINTER;
}

// A reference to the instantiated object can be obtained with the class name +
public static void main(String[] args) {
    // Get the object of the enumerated class
    Season season = Season.spring;
    // The output is: spring
    System.out.println(season);
    // The Season. Spring can be used as a constant
}

//2. Enum classes can also define constructors, attributes, and methods.
// The constructor can only be private (default is private)
public enum Season {
    spring("Spring"."Green"),
    SUMMER("Summer"."Orange"),
    AUTUMN("Autumn"."Yellow"),
    WINTER("Winter"."White");

    private final String name;
	private final String color;
    
    Season(String name,String color) {
        this.name = name;
        this.color = color;
    }
    
    public String getName(a) {
        return name;
    }

    public String getColor(a) {
        returncolor; }}// A reference to the instantiated object can be obtained with the class name +
public static void main(String[] args) {
    Season season = Season.spring;
    // The output is green
    System.out.println(season.getColor());
    System.out.println(Season.spring.getColor());
}


Copy the code

1.3 Enumerate common methods of classes

  • These methods inherit fromjava.lang.Enumclass
// 1.toString () : Returns the name of the enumeration class object
System.out.println(season.toString());
// Result: spring

//2. values(): Returns an array of enumerated class objects
// Note: yes enum class name. values()
 System.out.println(Season.values());
// Result: [lenumtest.season; @2A098129

for (Season season1 : Season.values()){
	System.out.println(season1);
}
// loop output content;
/*spring SUMMER AUTUMN WINTER*/


//3. valueOf(String objName): Returns the object of the enumeration class whose object name is objName.
// If there is no enumeration object of objName, throw an exception: IllegalArgumentException
Season winter = Season.valueOf("WINTER");
System.out.println(winter);
// result: WINTER
Copy the code

1.4 How to implement the interface by enumerating class objects?

interface Info{
    void show(a);
}

// Enumerate classes using the enum keyword
enum Season1 implements Info{
    SPRING("Spring"."Spring Blossoms") {@Override
        public void show(a) {
            System.out.println("Where is spring?");
        }
    },
    SUMMER("Summer"."Summer heat.") {@Override
        public void show(a) {
            System.out.println("The ningxia");
        }
    },
    AUTUMN("Autumn"."Crisp autumn air") {@Override
        public void show(a) {
            System.out.println("Autumn never comes back.");
        }
    },
    WINTER("Winter"."Ice and Snow") {@Override
        public void show(a) {
            System.out.println("About the winter."); }}; }Copy the code

2. Commonly used Java classes

2.1 the String class

2.1.1 to introduce

  • String: string, use a pair""Cause to express;
  • * * declared as Stringfinal* *,uninheritable
  • The String to achieve theSerializableInterface: indicates that the string isSupport serialization. To achieve theComparableInterface: indicates a StringYou can compare the size
  • Final char[] value is defined inside a String to store String data

2.1.2 Common methods

  • Vision problem, I feel commonly used on the first few.

  • String str = "Hello World !"
        
    //1. Check if it is an empty string
    boolean isEmpty(a);
    //2. Compare whether the contents of strings are the same: "hello". Equals (STR);
    boolean equals(Object obj);
    //3. Return a new string, which is the substring of the string from beginIndex to the end.
    String substring(int beginIndex);
    //4. Returns a new string that is a substring of the string from beginIndex to endIndex(not included).
    String substring(int beginIndex, int endIndex);
    //5. Tests whether the string starts with the specified prefix
    boolean startsWith(String prefix);
    Return true if and only if this string contains the specified sequence of char values
    boolean contains(CharSequence s);
    //7. Returns a new string obtained by replacing all occurrences of oldChar in the string with newChar.
    String replace(char oldChar, char newChar);
    //8. Replace the substring of the given regular expression that this string matches with the given replacement.
    String replaceAll(String regex, String replacement);
    //9. Split the string based on the match of the given regular expression.
    String[] split(String regex);
    / / String [] numberArr = "1, 2, 3, 4," split (", ");
    
    // Returns the length of the string
    int length(a);
    // Returns the character at an index
    char charAt(int index);
    // Convert all characters in String to lowercase
    String toLowerCase(a);
    // Convert all characters in String to uppercase
    String toUpperCase(a);
    // Returns a copy of the string, ignoring whitespace before and after the first letter of the string
    String trim(a);
    // Like equals, ignore case
    boolean equalsIgnoreCase(String anotherString);
    // Concatenates the specified string to the end of the string. That's the same thing as using +
    String concat(String str);
    // Compare the size of two strings,"hello". CompareTo (STR);
    int compareTo(String anotherString);
    // Tests whether the string ends with the specified suffix
    boolean endsWith(String suffix);
    // Tests whether the substring of this string starting at the specified index starts with the specified prefix, with the index starting at 0
    boolean startsWith(String prefix, int toffset);
    /*	String str = "Hello World !";
    	System.out.println(str.startsWith("Wo",6));//true
     */
    // Returns the index of the first occurrence of the specified substring in this string
    int indexOf(String str);
    // Returns the index at the first occurrence of the specified substring in this string, starting with the specified index
    int indexOf(String str, int fromIndex);
    // Returns the index of the rightmost occurrence of the specified substring in the string
    int lastIndexOf(String str);
    // Returns the index of the last occurrence of the specified substring in the string, starting with the specified index
    int lastIndexOf(String str, int fromIndex);
    // Note: Both indexOf and lastIndexOf methods return -1 if not found
    
    / / replace:
    // Replace the first substring matching the given regular expression with the given replacement.
    String replaceFirst(String regex, String replacement);
    
    / / match:
    // Tells whether this string matches the given regular expression.
    boolean matches(String regex);
    
    / / section:
    // Split the string according to the given regular expression, no more than limit, if more than, all the rest into the last element.
    String[] split(String regex, int limit);
    Copy the code

2.2 StringBuffer and StringBuilder

2.2.1 comparison

  • Comparison of String, StringBuffer, StringBuilder

    • String:Immutable sequence of characters; The underlying usechar[]storage
    • StringBuffer:Mutable character sequences;Thread safetyThe,The efficiency ofLow; The underlying usechar[]storage
  • StringBuilder: mutable character sequences; Jdk5.0 new, thread unsafe, high efficiency; The bottom layer uses char[] for storage

2.2.2 Capacity Expansion Problems

  • If the underlying array of data you want to add is no longer fit, you need to expand the underlying array. By default, it is expanded by 2 + 2, and the elements of the original array are copied into the new array.

2.2.3 Execution efficiency

  • The execution efficiency of the three:

    • Order from high to low: StringBuilder > StringBuffer > String;
    • But I always use StringBuffer, right?

2.2.4 Common methods

  • StringBuffer sb = new StringBuffer();
    / / add: sb. Append (XXX);
    append(xxx);
    / / delete:
    delete(int start,int end);
    deleteCharAt(int index);
    // Delete the last character: sb.deletecharat (sb.length-1);
    / / change:
    setCharAt(int n ,char ch) / replace(int start, int end, String str)
    / / check:
    charAt(int n )
    / / insert:
    insert(int offset, xxx)
    / / length:
    length();
    Copy the code

2.3 Time-based apis

2.3.1 Obtaining the Current System time

  • CurrentTimeMillis () in the System class

    long time = System.currentTimeMillis();
    // Returns the time difference in milliseconds between the current time and 00:00:00:00 on January 1, 1970.
    // This is called a timestamp
    Copy the code

2.3.2 Java. Util. The Date class

  • Constructor 1: Date() : creates a Date object corresponding to the current time
    Date date = new Date();
    Constructor 2: Creates a Date object with the specified number of milliseconds
    Date date = new Date(35235325345L);
    //System.out.println(date.toString()); 
    Sat Feb 13 03:35:25 CST 1971
    Copy the code

2.3.3 Java. Text. SimpleDataFormat class

  • Format: format();

  • Analytic: parse ();

    //1. Format: date --> string
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    String format1 = sdf1.format(date);/ / format
    System.out.println(format1);/ / the 2019-02-18 11:48:27
    
    //2. Parse: reverse process of formatting, string --> date
    // The string must be in a format recognized by SimpleDateFormat (as indicated by the constructor argument).
    // Otherwise, throw an exception
    Date date2 = sdf1.parse("The 2020-02-18 11:48:27");
    System.out.println(date2);
    Copy the code

2.3.4 Calendar Class: Calendar class

You’ve seen it in a lot of date utility classes.

Never used. Write after you’ve used it…

2.4 the System class

  • The System class represents the System, and many of the system-level properties and control methods are placed inside the class. This class is located in the java.lang package.

  • Because the constructor of the ** class is private, objects of the class cannot be created, that is, the class cannot be instantiated. Its internal member variables and methods are static, so it can be easily called.

  • Methods:

    native long currentTimeMillis(a);
    void exit(int status);
    void gc(a);
    String getProperty(String key); . I've only used system.out.println () and currentTimeMillis(); Gc () is for garbage collection, I'll write it after I use it...Copy the code

2.5 Math class

  • java.lang.MathA series of static methods are provided for scientific calculations.The arguments and return values of its methods are typically of type double.

3. The annotation

  • Comment: These are special tags in code that can be read and processed at compile, classload, and runtime.

  • Using annotations, you can embed supplementary information in the source file without changing the original logic.

  • Annotations are used extensively in frameworks, but rarely in JavaEE.

  • There are plenty of annotations to learn about Spring.