Java advanced feature learning (super detailed) II (common practical classes)

1. Enumeration

1.1 Reasons for enumeration

        Scenario: If an illogical type appears while defining an attribute, it needs to be replaced by an enumeration type (in general terms, it is stipulated that some parameters are in a certain fixed data, and these parameters are not allowed to be other values)

1.2 Create an enumeration

An enumeration refers to a type consisting of a fixed set of constants

Enumeration keyword: enum

public enum Genders {
	Male,Female;
}

1.3 Using enumerations

public class Student2 {
	private Genders sex;

	public Genders getSex() {
		return sex;
	}

	public void setSex(Genders sex) {
		this.sex = sex;
	}

	public static void main(String[] args) {
		 Student2 student2 = new Student2();
        student2.setSex(Genders.MALE);
        System.out.println(student2.getSex());	}
}

1.4 Using enumerations - 2

Define the student class, the attribute is grade, use the enumeration type to realize the mapping of excellent, good, pass, fail and A, B, C, D

public enum Achievement {
    excellent("优秀"),good("良好"),pass("及格"),fail("不及格");
    private String name;

    Achievement() {
    }

    Achievement(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Student {
    private Achievement achievement;

    public Achievement getAchievement() {
        return achievement;
    }

    public void setAchievement(Achievement achievement) {
        this.achievement = achievement;
    }

    public static void main(String[] args) {
        Student student = new Student();
        student.setAchievement(Achievement.excellent);
        System.out.println(student.getAchievement().getName());
    }
}

1.5 Using enumerations - 3

public class Student1 {
    private String score;

    public Student1() {
    }

    public Student1(String score) {
        this.score = score;
    }

    public String getScore() {
        return score;
    }

    public void setScore(String score) {
        this.score = score;
    }

    public static void main(String[] args) {
        Student1 student = new Student1();
        student.setScore(Achievement.excellent.getName());
        System.out.println(student.getScore());
    }
}

2. Packaging

2.1 Definition

Each basic data type has its own packaging type in the java.lang package, such as the packaging type of int type is Integer, the packaging type of char type is Character, etc.

2.2 Function of packaging type

  1. The packaging type provides a series of methods, such as conversion between basic data types and packaging types, etc.
  2. Only data of packaging type can be stored in the collection, and data of basic type cannot be stored

2.3 Implementation of the constructor of the wrapper type

 (1) Convert basic data types to wrapper types:

    public static void main(String[] args) {
        int a = 12;
        //将基本数据类型int类型的a转换成了包装类型Integer
        Integer integer = new Integer(a);

         byte b = 1;
         Byte by = new Byte(b);

         short s = 12;
         Short sh = new Short(s);

         long l = 12;
         Long lo = new Long(l);

    }

(2) Convert string type to wrapper type

In addition to the Character type, you can use the constructor to convert the string type to the wrapper type

    public static void main(String[] args) {
        String a = "123";
        //字符串类型转换成Integer类型
        Integer integer = new Integer(a);
        System.out.println(integer);

        Double d = new Double(a);
    }

Remarks: special case of Boolean

2.4 Common methods

Use the xxvalue() method of the packaging type to realize the conversion of the packaging type to the basic data type

        Boolean b = new Boolean("True");
        boolean b1 = b.booleanValue();
        System.out.println(b);

Basic data type conversion to string type

        int a = 3;
        //利用包装类型中的toString() 实现 将基本数据类型转换成字符串类型
        String b = Integer.toString(a);

Convert string type to basic data type (use parseXX() of package type except Character)

        String a = "133";
        int aa = Integer.parseInt(a);

Basic data types are converted to wrapper types (using valueOf() in wrapper types)

        int aa = 12;
        Integer integer1 = new Integer(aa);
        Integer integer3 = Integer.valueOf(aa);

Convert the string type to a wrapper type (use valueOf() in the wrapper type except Character)

        String a = "1223";
        Integer integer = new Integer(a);
        Integer integer2 = Integer.valueOf(a);

2.5 Boxing and unboxing

        Boxing: Objects of primitive types converted to wrapper types (automatically converted!)

        Unboxing: Wrapper class object converted to primitive type value (automatic conversion!)

        //基本数据类型
        int a = 3;

        //基本数据类型自动转换成包装类型--》装箱
        Integer b = a;

        //包装数据类型
        Integer aa = 3;

        //包装数据类型自动转换成基本类型--》装箱
        int bb = aa;

Remarks : int and Integer attributes are assigned different values ​​by default when they are initialized

        Attributes of type int are assigned a default value of 0

        Integer type attributes are assigned null by default


3.String

3.1 String basic syntax

  1. Definition: store a string
  2. 语法:String a = “”;    String b = new String();    String c = new String(“”);
  3. Package path: java.lang package
  4. Remarks: String a = "";//String variables are stored in the method area (in the constant pool)

                    String c = new String(""); String variables are stored in the heap

3.2 Common methods

3.2.1 length()

length(): returns the length of this string

String a = "helloworld";
System.out.println(a.length());

Remarks: array length, array.length property

           Collection length: list.size() method

3.2.2 equals()

equals(): compares whether the contents of the strings are the same

==: The comparison is whether the memory addresses are the same

int a = 1;
int b = 1;
System.out.println(a==b); //这里的结果是true
System.out.println(a.equals(b)); //这里编译报错,equals不是是基本类型的方法
System.out.println("乔尼".equals("jojo"));//这里的结果是false

For the comparison of basic types, use == instead of equals

Here I want to expand on the difference between == and equals:

        String a = "11";
        String b = "11";
        String c = new String("11");
        System.out.println(a==b);//结果true
        System.out.println(a.equals(b));//结果true
        System.out.println(a==c);//结果false
        System.out.println(a.equals(c));//结果true

In the above example, a, b, and c should all be the same in our opinion, why can there be false?

Here we have to start with the storage state of variables. Basic types of variables are stored in the stack, while reference types are stored in the heap, but they are mapped to an address in the stack.

== The comparison is whether the content of the variable in the stack is the same. For the reference type, it is to compare whether the memory address is the same. The above-mentioned a and b have not opened up new space, and the addresses in the stack are the same, while c Opening up a new space is equivalent to opening up a new space in the heap, and the address in the stack is naturally different from b and c

equals compares whether the contents in the heap are the same, so the above are all true

3.2.3 equalsIgnoreCase()

Definition: Compare this String with another String, regardless of case

String a = "hello";
String b = "Hello";
System.out.println(a.equalsIgnoreCase(b));//结果为true

3.2.4 toLowerCase()

Definition: Convert all characters in String to lowercase [uppercase to lowercase, lowercase unchanged]

        String st = "Jojo".toLowerCase();//st值为jojo

3.2.5 toUpperCase()

Definition: Convert all characters in String to uppercase [lowercase to uppercase, uppercase unchanged]

        String st = "Jojo".toLowerCase();//st值为JOJO

 

3.2.6 concat()

Definition: splicing two strings together, the same function as +

String st1 = "hello"+"world";
String st2 = "hello".concat("world");

 

3.2.7 trim()

Definition: Returns a copy of the string, ignoring leading and trailing whitespace

String st = "   hello world   ".trim();//st值为hello world

3.2.8 indexOf() 

Definition: Returns the index of the first occurrence of the specified string in this string, or -1 if it does not appear

        String s = "hello world";
        System.out.println(s.indexOf("w"));//结果为6,索引从0开始算起,空格也算一位

 

3.2.9 substring() 

substring(int beginIndex):

Returns a substring starting at the character at the specified index and ending at the end of this string

        String s = "hello world";
        System.out.println(s.substring(7));//结果为orld,索引从0开始算起,空格也算一位

substring(int beginIndex,int endIndex)

Returns a substring starting at the specified beginIndex up to the characters at index endIndex - 1. Therefore, the length of the substring is endIndex - beginIndex [the values ​​that can be obtained are left-closed and right-open intervals]

        String s = "hello world";
        System.out.println(s.substring(7,8));//结果为o,索引从0开始算起,空格也算一位

3.2.10 split()

 Definition: split a string

        String s = "hello world";
        String []st = s.split(" ");//以空格分割字符串s,返回一个字符串数组
        for(String s1 : st){
            System.out.println(s1);//结果为依次输出hello和world
        }


4.StringBuffer

4.1 The reason for StringBuffer generation

Scenario: String is an unmodifiable string, and the splicing efficiency is low, so StringBuffer needs to be used instead

The + or concat method of String returns a new String string, so it is inefficient, and StringBuffer modifies itself.

4.2 StringBuffer Declaration

StringBuffer buffer = new StringBuffer(“hello”);
StringBuffer buffer = new StringBuffer();

4.3 Common methods

4.3.1 append()

Append the new string to the end of the original string

        StringBuffer buffer = new StringBuffer("jojo");
        buffer.append("hello");
        System.out.println(buffer);//输出jojohello

 

 4.3.2 insert()

Insert a character string at a certain index position of the original character string, and the characters after the index are moved backwards one by one

        buffer.insert(2, "123");
        System.out.println(buffer);//输出jo123jo

5. Date

5.1 Get the current date

        Date date = new Date();
        System.out.println(date);//输出当前时间

 

5.2 Convert string type to Date type

Use the parse() method of SimpleDateFormat

        String s = "2023-12-1 17:12:1";
        SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd hh:mm:dd");
        Date date1 = format.parse(s);
        System.out.println(date1);

 

5.3 Convert Date type to String type

Using the format() method of SimpleDateFormat

        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd hh:mm:dd");
        String datest = format.format(date);
        System.out.println(datest);

Guess you like

Origin blog.csdn.net/jojo_oulaoula/article/details/131250524