Notes: common classes

Posted by Mchl on Tue, 04 Jan 2022 21:55:46 +0100

Catalogue

1, String related classes:

Creation of String object:

String attribute:

String common methods:

Sting and transformation of basic data types and packaging classes:

Conversion between String and char []:

Conversion between String and byte []:

String related classes: StringBuffer, StringBuilder:

Summary:

2, Date time API before JDK8

currentTimeMillis() in System class;

 java.util.Date and subclass Java sql. Date1.

Simpledateformatusing simpledateformat:

Use of Instant

4, Java comparator:

Use of Comparator interface: custom sorting

          5, System class:

 6, Math class:

VII. BigInteger and BigDecimal:

1, String related classes:

String attribute
String: a string represented by a pair of "".
1.String is declared as final and cannot be inherited
2.String implements the Serializable interface: it means that the string supports serialization.
The Comparable interface is implemented: it means that strings can compare sizes
3. final char[] value is defined inside string to store string data
4.String: represents an immutable character sequence. Abbreviation: non variability.
reflect:

When the string is re assigned, the assigned memory area needs to be rewritten, and the original value cannot be used for assignment.
When connecting an existing string, you also need to assign a value to the memory area again. The original value cannot be used for assignment.
When calling the replace() method of String to modify the specified character or String, you also need to reassign the memory area assignment, and the original value cannot be used for assignment.
5. Assign a value to a string by literal (different from new). At this time, the string value is declared in the string constant pool.
6. Strings with the same content will not be stored in the string constant pool.
 

public class StringTest {

    @Test
    public void test1(){
        String s1="abc";//Definition of literal quantity
        String s2="abc";
        System.out.println(s1==s2);//Compare address values, true
        s1="hello";
        System.out.println(s1==s2);//false
        System.out.println(s1);//hello
        System.out.println(s2);//abc
        System.out.println("*****************");
        String s3="abc";
        s3+="def";
        System.out.println(s3);//abcdef
        System.out.println(s2);//abc
        System.out.println("*****************");
        String s4 = "abc";
        String s5 = s4.replace('a', 'm');
        System.out.println(s4);//abc
        System.out.println(s5);//mbc
    }
}

Creation of String object:


Instantiation method of String:
Method 1: defined by literal quantity
Mode 2: through the new + constructor

Interview question: String s = new String("abc"); How many objects are created in memory?
Two: one is the new structure in the heap space, and the other is the data in the constant pool corresponding to char []: "abc"
 

    public void test2(){
        //By literal definition:
        // At this time, the data javaEE of s1 and s2 is declared in the string constant pool in the method area.
        String s1 = "javaEE";
        String s2 = "javaEE";
        //Through the new + constructor: the address values saved in s3 and s4 at this time,
        // Is the address value corresponding to the data after opening up space in the heap space.
        String s3 = new String("javaEE");
        String s4 = new String("javaEE");
        System.out.println(s1 == s2);//true
        System.out.println(s1 == s3);//false
        System.out.println(s1 == s4);//false
        System.out.println(s3 == s4);//false
        System.out.println("***********************");
        Person p1 = new Person("Tom",12);
        Person p2 = new Person("Tom",12);
        Person p3 = new Person(new String("Tom"),12);

        System.out.println(p1.name.equals(p2.name));//true
        System.out.println(p1.name == p2.name);//true
        System.out.println(p1.name==p2.name);//true, pointing to the same address in the constant pool
		System.out.println(p1.name==p3.name);//false
        p1.name = "Jerry";
        System.out.println(p2.name);//Tom

    }

String attribute:


1. The splicing results of constants and constants are in the constant pool. And constants with the same content will not exist in the constant pool.
2. As long as one of them is a variable, the result is in the heap (similar to new).
3. If the result of splicing calls the intern() method, the return value is in the constant pool

@Test
    public void test5(){
        String s1 = "javaEEhadoop";
        String s2 = "javaEE";
        String s3 = s2 + "hadoop";
        System.out.println(s1 == s3);//false

        final String s4 = "javaEE";//s4: constant
        String s5 = s4 + "hadoop";
        System.out.println(s1 == s5);//true
    }
    @Test
    public void test4(){
        String s1 = "javaEE";
        String s2 = "hadoop";

        String s3 = "javaEEhadoop";
        String s4 = "javaEE" + "hadoop";
        String s5 = s1 + "hadoop";
        String s6 = "javaEE" + s2;
        String s7 = s1 + s2;

        System.out.println(s3 == s4);//true
        System.out.println(s3 == s5);//false
        System.out.println(s3 == s6);//false
        System.out.println(s3 == s7);//false
        System.out.println(s5 == s6);//false
        System.out.println(s5 == s7);//false
        System.out.println(s6 == s7);//false

        String s8 = s6.intern();//Return the "Java EE Hadoop" that already exists in the constant value used by s8
        System.out.println(s3 == s8);//true

    }

String common methods:

 

When the values of str (index) and of (STR of) are the same?
Case 1: there is a unique str. Case 2: STR does not exist

Sting and transformation of basic data types and packaging classes:


String -- > basic data type, wrapper class: call the static method of wrapper class: parseXxx(str)
Basic data type, wrapper class -- > String: call valueOf(xxx) overloaded by String

@Test
    public void test1(){
        String s1="123";
        Integer i=Integer.parseInt(s1);
        System.out.println(i);
        String s2=String.valueOf(i);
        String s3=i+"";
    }

Conversion between String and char []:


String -- > char []: call toCharArray() of string
Char [] -- > String: call the constructor of String

@Test
    public void test2(){
        String s1="abc123";
        char[] charArray=s1.toCharArray();
        for (int i = 0; i <charArray.length ; i++) {
            System.out.println(charArray[i]);
        }
        char[] arr=new char[]{'h','e','l','l','o'};
        String s2=new String(arr);
        System.out.println(s2);
    }

Conversion between String and byte []:

Code: String -- > byte []: call getBytes() of string
Decoding: byte [] -- > String: call the constructor of String
Encoding: String -- > bytes (understandable - > incomprehensible binary data)
Decoding: inverse process of encoding, byte -- > string (incomprehensible binary data - > understandable)
Note: during decoding, the character set used for decoding must be consistent with the character set used for encoding, otherwise garbled code will appear.
 

@Test
    public void test3() throws UnsupportedEncodingException {
        String s1="abc123 China";
        byte[] bytes=s1.getBytes();//Use the default character set for encoding. One Chinese character has three bytes
        System.out.println(Arrays.toString(bytes));

        byte[] gbks=s1.getBytes("gbk");//Use gbk character set for encoding. One Chinese character has two bytes
        System.out.println(Arrays.toString(gbks));

        System.out.println("*************");
        String s2=new String(bytes);//Decode using the default character set.
        System.out.println(s2);
        String s3=new String(gbks);//Garbled code. Cause: the encoding set and decoding set are inconsistent!
        System.out.println(s3);

        String s4=new String(gbks,"gbk");
        System.out.println(s4);//No garbled code. Reason: the encoding set and decoding set are consistent!


    }

String related classes: StringBuffer, StringBuilder:

1. What are the similarities and differences among String, StringBuffer and StringBuilder?


String: immutable character sequence; The bottom layer uses char [] storage
StringBuffer: variable character sequence; Thread safety and low efficiency; The bottom layer uses char [] storage
StringBuilder: variable character sequence; jdk5.0 new, thread unsafe, high efficiency; The bottom layer uses char [] storage


2. Compare the efficiency of String, StringBuffer and StringBuilder:


Arrange from high to low: StringBuilder > StringBuffer > string

public class StringBufferTest {
    @Test
    public void test2(){
        String str=new String();//char[] value = new char[0];
        String str1=new String("abc");//char[] value = new char[]{'a','b','c'};

        StringBuffer sb1=new StringBuffer();//char[] value = new char[16]; The bottom layer creates an array with a length of 16.
        System.out.println(sb1.length());//0
        sb1.append('a');//value[0] = 'a';
        sb1.append('b');//value[1] = 'b';

        StringBuffer sb2=new StringBuffer("abc");//char[] value = new char["abc".length() + 16];
        //Question 1
        System.out.println(sb2.length());//3
        //Question 2 Capacity expansion: if the underlying array of data to be added cannot hold enough, the underlying array needs to be expanded.
        //By default, the capacity is expanded to 2 times + 2 of the original capacity, and the elements in the original array are copied to the new array.

       //Guiding significance: it is recommended to use StringBuffer(int capacity) or StringBuilder(int capacity) in development

    }
    @Test
    public void test1(){
        StringBuffer sb1=new StringBuffer("abc");
        sb1.setCharAt(0,'m');
        System.out.println(sb1);//mbc

        StringBuffer sb2=new StringBuffer();
        System.out.println(sb2.length());//0
    }

}

Summary:

Add: append(xxx)
Delete: delete(int start,int end)
Change: setcharat (int n, char CH) / replace (int start, int end, string STR)
Query: charAt(int n)
Insert: insert(int offset, xxx)
Length: length();
Traversal: for() + charAt() / toString()

2, Date time API before JDK8

currentTimeMillis() in System class;

public class DateTimeTest {
    @Test
    public void test1(){
        long time=System.currentTimeMillis();
        //Returns the time difference in milliseconds between the current time and 0:0:0:0 on January 1, 1970.
        //This is called a timestamp
    }
}

 java.util.Date and subclass Java sql. Date
1. Use of two constructors
->Constructor 1: Date(): creates a Date object corresponding to the current time
->Constructor 2: create a Date object with a specified number of milliseconds
2. Use of the two methods
->Tostring(): displays the current year, month, day, hour, minute and second
->Gettime(): gets the number of milliseconds corresponding to the current Date object. (timestamp)
3. java.sql.Date corresponds to a variable of date type in the database
->How to instantiate
->How to convert Java util. Convert Date object to Java sql. Date object
 

@Test
    public void test2(){
        //Constructor 1: Date(): creates a Date object corresponding to the current time
        Date date1=new Date();//Wed Jul 15 18:37:00 CST 2020
        System.out.println(date1);
        System.out.println(date1.toString());//Wed Jul 15 18:37:00 CST 2020
        System.out.println(date1.getTime());//1594809420739
        //Constructor 2: create a Date object with a specified number of milliseconds
        Date date2=new Date(1594809420739L);
        System.out.println(date2.toString());//Wed Jul 15 18:37:00 CST 2020
        //Create Java sql. Date object
        java.sql.Date date3=new java.sql.Date(1594809420739L);
        System.out.println(date3);//2020-07-15

        //How to convert Java util. Convert Date object to Java sql. Date object
        //Case 1:
        Date date4=new java.sql.Date(1594809420739L);
        java.sql.Date date5=(java.sql.Date)date4;
        //Case 2:
        Date date6=new Date();
        java.sql.Date date7=new java.sql.Date(date6.getTime());
    }

 SimpleDateFormat
Use of SimpleDateFormat: SimpleDateFormat formats and parses the Date class
1. Two operations:
1.1 format: date - > string
1.2 parsing: the reverse process of formatting, string - > date
2. Instantiation of simpledateformat
 

@Test
    public void test3() throws ParseException {
        //Instantiate SimpleDateFormat: use default constructor
        SimpleDateFormat sdf=new SimpleDateFormat();
        //Format: date -- > string
        Date d1=new Date();
        System.out.println(d1);//Wed Jul 15 18:50:14 CST 2020

        String format=sdf.format(d1);
        System.out.println(format);//20-7-15 6:50 PM
        //Parsing: inverse process of formatting, string -- > date
        String str="20-12-12 11 a.m:34";
        Date d2=sdf.parse(str);
        System.out.println(d2);//Sat Dec 12 11:34:00 CST 2020
        //*************Format and parse as specified: call the constructor with parameters*****************
        //SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //format
        String format1=sdf1.format(d1);
        System.out.println(format1);//2020-07-15 06:52:54
        //Parsing: the string must conform to the format recognized by SimpleDateFormat (reflected by constructor parameters),
        //Otherwise, throw the exception
        Date d3=sdf1.parse("2020-07-15 06:52:54");
        System.out.println(d3);
    }

III. new date and time API in JDK8:

Use of LocalDate, LocalTime and LocalDateTime
explain:
1.LocalDateTime is used more frequently than LocalDate and LocalTime
2. Similar to Calendar

@Test
    public void test6(){
        //Offset
        Date d1=new Date(2020,9,8);
        System.out.println(d1);//Fri Oct 08 00:00:00 CST 3920
        //now(): get the current date, time, date + time
        LocalDate localDate=LocalDate.now();
        LocalTime localTime=LocalTime.now();
        LocalDateTime localDateTime=LocalDateTime.now();
        System.out.println(localDate);//2020-07-15
        System.out.println(localTime);//22:36:50.632
        System.out.println(localDateTime);//2020-07-15T22:36:50.632
        //of(): set the specified year, month, day, hour, minute and second. No offset
        LocalDateTime localDateTime1=LocalDateTime.of(2020,10,6,13,23,00);
        System.out.println(localDateTime1);//2020-10-06T13:23
        //getXxx(): get related properties
        System.out.println(localDateTime.getDayOfMonth());
        System.out.println(localDateTime.getDayOfWeek());
        System.out.println(localDateTime.getMonth());
        System.out.println(localDateTime.getMonthValue());
        System.out.println(localDateTime.getMinute());
        //Reflect immutability
        //withXxx(): set related properties
        LocalDate localDate1=localDate.withDayOfMonth(22);
        System.out.println(localDate);//2020-07-15
        System.out.println(localDate1);//2020-07-22

        LocalDateTime localDateTime2=localDateTime.withHour(4);
        System.out.println(localDateTime);
        System.out.println(localDateTime2);

        LocalDateTime localDateTime3=localDateTime.plusMonths(3);
        System.out.println(localDateTime);
        System.out.println(localDateTime3);

        LocalDateTime localDateTime4=localDateTime.minusMonths(6);
        System.out.println(localDateTime);
        System.out.println(localDateTime4);
    }

 

Use of Instant


Similar to Java util. Date class

@Test
    public void test7(){
        //now(): get the standard time corresponding to the original meridian
        Instant instant=Instant.now();
        System.out.println(instant);//2020-07-15T14:54:13.660Z
        //Add offset of time
        OffsetDateTime offsetDateTime=instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2020-07-15T22:54:13.660+08:00
        //Toepochmili(): get the number of milliseconds since 0:0:0 (UTC) on January 1, 1970 -- > getTime() of date class
        long milli=instant.toEpochMilli();
        System.out.println(milli);//1594824963760
        //Ofepochmili(): get the Instant instance -- > date (long millisecond) by the given number of milliseconds
        Instant instant1=Instant.ofEpochMilli(1594824963760L);
        System.out.println(instant1);//2020-07-15T14:56:03.760Z
    }

 

DateTimeFormatter: formats or parses date and time


Similar to SimpleDateFormat

@Test
    public void test8(){
        //Method 1: predefined standard format. E.g. ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter formatter=DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //Format: date -- > string
        LocalDateTime localDateTime=LocalDateTime.now();
        String s1=formatter.format(localDateTime);
        System.out.println(localDateTime);//2020-07-15T23:00:37.593
        System.out.println(s1);//2020-07-15T23:00:37.593
        //Parsing: String -- > date
        TemporalAccessor parse=formatter.parse("2020-07-15T23:00:37.593");
        System.out.println(parse);//{},ISO resolved to 2020-07-15T23:00:37.593
        //        Mode 2:
        //Localization related formats. For example: ofLocalizedDateTime()
        //FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: for LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        //format
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//July 15, 2020 11:03:59 PM


//      Localization related formats. For example: ofLocalizedDate()
//      FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: applicable to LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
        //format
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);//2020-7-15
        // Key point: Method 3: custom format. For example: ofPattern("yyyy MM DD HH: mm: SS")
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //format
        String str4 = formatter3.format(LocalDateTime.now());
        System.out.println(str4);//2020-07-15 11:05:12

        //analysis
        TemporalAccessor accessor = formatter3.parse("2020-07-15 11:05:12");
        System.out.println(accessor);//{NanoOfSecond=0, MicroOfSecond=0, HourOfAmPm=11, MinuteOfHour=5, MilliOfSecond=0, SecondOfMinute=12},ISO 
    }

 

4, Java comparator:

1, Note: under normal circumstances, objects in Java can only be compared: = = or! =. Cannot use > or <
However, in the development scenario, we need to sort multiple objects. By implication, we need to compare the size of objects.
How? Use either of the two interfaces: Comparable or Comparator
2, Comparison between Comparable interface and Comparator:
Once the method of the Comparable interface is fixed, it can ensure that the objects of the implementation class of the Comparable interface can be compared in size at any position.
The Comparator interface is temporary.
Example of using the Comparable interface: natural sorting
1. For example, String and wrapper classes implement the Comparable interface, rewrite the compareTo(obj) method, and give a way to compare the sizes of two objects.
2. After rewriting the compareTo() method for String and wrapper classes, they are arranged from small to large
3. Rules for rewriting compareTo(obj):
If the current object this is greater than the formal parameter object obj, a positive integer is returned,
If the current object this is less than the formal parameter object obj, a negative integer is returned,
Returns zero if the current object this is equal to the parameter object obj.
4. For custom classes, if sorting is required, we can let the custom class implement the Comparable interface and override the compareTo(obj) method.
Indicate how to sort in the compareTo(obj) method
 

public class CompareTest {
    @Test
    public void test1(){
        String[] arr=new String[]{"aa","cc","bb"};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));//[aa, bb, cc]
    }
    @Test
    public void test2(){
        Goods[] arr = new Goods[5];
        arr[0] = new Goods("lenovoMouse",34);
        arr[1] = new Goods("dellMouse",43);
        arr[2] = new Goods("xiaomiMouse",12);
        arr[3] = new Goods("huaweiMouse",65);
        arr[4] = new Goods("microsoftMouse",43);
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
class Goods implements Comparable{
    private String name;
    private int price;

    public Goods(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public int getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
    //Specify the way to compare the size of goods: sort according to the price from low to high, and then sort according to the product name from high to low
    @Override
    public int compareTo(Object o) {
        if(o instanceof Goods){
            Goods goods=(Goods)o;
            //Mode 1:
            if(price>goods.price){
                return 1;
            }else if(price<goods.price){
                return -1;
            }else{return -name.compareTo(goods.name);}
            //Mode 2:
//           return Double.compare(this.price,goods.price);
        }
        throw new RuntimeException("The data type passed in is inconsistent!");
    }
}

Use of Comparator interface: custom sorting


1. Background:
When the element type does not implement Java Lang. comparable interface and inconvenient to modify code,
Or implement Java The collation of lang.comparable interface is not suitable for the current operation,
Then consider using Comparator objects to sort
2. Rewrite the compare(Object o1,Object o2) method to compare the sizes of o1 and o2:
If the method returns a positive integer, o1 is greater than o2;
If 0 is returned, it means equal;
Returns a negative integer indicating that o1 is less than o2.
 

 @Test
    public void test3(){
        String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"};
        Arrays.sort(arr,new Comparator(){

            //Arrange strings in descending order
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof String && o2 instanceof  String){
                    String s1 = (String) o1;
                    String s2 = (String) o2;
                    return -s1.compareTo(s2);
                }
//                return 0;
                throw new RuntimeException("The data type entered is inconsistent");
            }
        });
        System.out.println(Arrays.toString(arr));
    }

@Test
    public void test4(){
        Goods[] arr = new Goods[6];
        arr[0] = new Goods("lenovoMouse",34);
        arr[1] = new Goods("dellMouse",43);
        arr[2] = new Goods("xiaomiMouse",12);
        arr[3] = new Goods("huaweiMouse",65);
        arr[4] = new Goods("huaweiMouse",224);
        arr[5] = new Goods("microsoftMouse",43);
        Arrays.sort(arr, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Goods && o2 instanceof  Goods){
                    Goods s1 = (Goods) o1;
                    Goods s2 = (Goods) o2;
                    if(s1.getName().equals(s2.getName())){
                        return -Double.compare(s1.getPrice(),s2.getPrice());
                    }else{
                        return s1.getName().compareTo(s2.getName());
                    }
                }
                throw new RuntimeException("The data type entered is inconsistent");
            }
        });
        System.out.println(Arrays.toString(arr));
    }

5, System class:

@Test
    public void test1() {
        String javaVersion = System.getProperty("java.version");
        System.out.println("java of version:" + javaVersion);

        String javaHome = System.getProperty("java.home");
        System.out.println("java of home:" + javaHome);

        String osName = System.getProperty("os.name");
        System.out.println("os of name:" + osName);

        String osVersion = System.getProperty("os.version");
        System.out.println("os of version:" + osVersion);

        String userName = System.getProperty("user.name");
        System.out.println("user of name:" + userName);

        String userHome = System.getProperty("user.home");
        System.out.println("user of home:" + userHome);

        String userDir = System.getProperty("user.dir");
        System.out.println("user of dir:" + userDir);

    }

6, Math class:

VII. BigInteger and BigDecimal:

BigInteger can represent an immutable integer of any precision

The general Float class and Double class can be used for scientific calculation or engineering calculation, but in commercial calculation,
It requires high digital accuracy, so Java is used math. BigDecimal class.
The BigDecimal class supports immutable signed decimal points of arbitrary precision.

@Test
    public void test2() {
        BigInteger bi = new BigInteger("1243324112234324324325235245346567657653");
        BigDecimal bd = new BigDecimal("12435.351");
        BigDecimal bd2 = new BigDecimal("11");
        System.out.println(bi);
//         System.out.println(bd.divide(bd2));
        System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));
        System.out.println(bd.divide(bd2, 25, BigDecimal.ROUND_HALF_UP));

    }

Topics: Java