1. String

1.1 Introduction

  • Basic properties: immutability. If you modify the contents of a String, you are reopening space and assigning a new value

  • If the assignment is literal, the string is stored in the constant pool of the method area. In a constant pool, strings with the same content are not kept, so if two strings have the same content, they point to the same address

    public class Test {
        public static void main(String[] args) {
            String s1 = "abc";
            String s2 = "abc";
            System.out.println(s1 == s2); // The output is true}}Copy the code
  • If created by new, it is stored in the heap, but the value in the object points to the constant pool

    public class Test {
        public static void main(String[] args) {
            String s1 = "abc";
            String s2 = "abc";
            String s3 = new String("abc");
            String s4 = new String("abc");
    
            System.out.println(s1 == s2); // true
            System.out.println(s1 == s3); // false
            System.out.println(s1 == s4); // false
            System.out.println(s3 == s4); // false}}Copy the code

  • In the case of string concatenation, if concatenation of variables is involved, it opens up new space in the heap

    public class Test {
        public static void main(String[] args) {
            String s1 = "Hello";
            String s2 = "World";
            final String s3 = "World";
    
            String s4 = "HelloWorld";           // Literal assignment directly to the constant pool
            String s5 = s1 + "World";           // Involves concatenation of variables, which opens up new space in the heap
            String s6 = "Hello" + s2;           / / same as above
            String s7 = s1 + s2;                / / same as above
            String s8 = "Hello" + s3;           // s3 is a final constant, a concatenation of two constants, pointing to the constant pool
            String s9 = "Hello" + "World";      // Constant and constant concatenation, pointing to the constant pool
            String s10 = (s1 + s2).intern();    // Intern () returns the address in the constant pool
    
            System.out.println(s4 == s5);       // false
            System.out.println(s4 == s6);       // false
            System.out.println(s4 == s7);       // false
            System.out.println(s4 == s8);       // true
            System.out.println(s4 == s9);       // true
            System.out.println(s4 == s10);      // true}}Copy the code

1.2 Type quasi change

  • String to primitive: call the parseXXX() method of the wrapper class corresponding to the primitive type

  • To convert a primitive type to String: call the string.valueof () method

  • String to char[] : Calls toCharArray() on String

  • Char [] converts to String: Puts char[] in the constructor of String

  • String to byte array: call the getBytes() method of String

  • Byte array to String: Puts the byte array into the String constructor

    public class Test {
        public static void main(String[] args) throws UnsupportedEncodingException {
            byte[] bytes = "Java learning".getBytes("gbk"); // The GBK character set encoding, the default is UTF-8
            String str = new String(bytes, "gbk");    // Decode according to GBK character set
            System.out.println(str);                  // Print "Java learning"}}Copy the code

1.3 Similarities and Differences between String, StringBuffer, and StringBuilder

Similarities:

  • Both are stored in char[]

Difference:

  • String: immutable sequence of characters
  • StringBuffer: Mutable sequence of characters, thread-safe (methods modified by synchronized), inefficient. Create a new array of characters with the size of 2 + 2, and copy the contents of the old array
  • StringBuilder: Mutable character sequences that are thread unsafe and efficient
  • StringBuilder > StringBuffer > String

1.4 sample

Gets the largest substring of two strings

/** * gets the largest substring * of two strings@paramStr1 The character string is 1 *@paramStr2 The string is 2 *@returnReturns the largest substring of two strings */
public String findMaxSameString(String str1, String str2) {
    if (str1 == null || str2 == null || str1.equals("") || str2.equals("")) {
        return null;
    }
    String maxStr;
    String minStr;
    if (str1.length() >= str2.length()) {
        maxStr = str1;
        minStr = str2;
    } else {
        maxStr = str2;
        minStr = str1;
    }
    int length = minStr.length();
    for (int flag = length; flag > 0; flag--) {
        for (int start = 0, end = flag - 1; end < length; start++, end++) {
            String temp = minStr.substring(start, end + 1);
            if (maxStr.contains(temp)) {
                returntemp; }}}return null;
}
Copy the code

2. Time related

2.1 Java. Util. Date

The constructor explain
Date() Create a Date object with the current ** timestamp (from 0 o ‘clock, January 1, 1970 to the present millisecond)**
Date(long date) Create a Date object with the specified timestamp
methods explain
toString() Display corresponding time
getTime() Get the corresponding timestamp

(Note: Java.sql.Date corresponds to the Date type in the database)

2.2 Java. Text. SimpleDateFormat

Used to format and parse the Date class.

public class Test {
    public static void main(String[] args) {
        // Create a SimpleDateFormat for a specific format
        // Format: date --> string
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String result = sdf.format(date);
        System.out.println(result);

        // Parse: string --> date
        String str = "2019-09-08";
        try {
            Date parse = sdf.parse(str);
            System.out.println(parse);
        } catch(ParseException e) { e.printStackTrace(); }}}Copy the code

The common letters stand for something like this (JDK 1.6 API)

2.3 Java. Util. Calendar

Calendar class, is an abstract class.

public class Test {
    public static void main(String[] args) {
        // Method 1: instantiate by its subclass
        Calendar calendar = new GregorianCalendar();

        // Method 2: instantiate using static methods
        Calendar calendar2 = Calendar.getInstance();

        / / the get () method
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));  / / output 8

        / / set () method
        calendar.set(Calendar.DAY_OF_MONTH, 10);
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));  / / output 10

        / / the add () method
        calendar.add(Calendar.DAY_OF_MONTH, 5);
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));  / / output 15
        
        // Convert to a Date object
        Date time = calendar.getTime();
        System.out.println(time);

        // Use the Date object to set the time for the Calendar class
        Date date = new Date();
        calendar.setTime(date);
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));  / / output 8}}Copy the code

2.4 LocalDate, LocalTime, and LocalDateTime

Time classes introduced in Java 8.

public class Test {
    public static void main(String[] args) {
        // All three classes have similar methods
        // The now() method is created to get the date, time, date, and time respectively
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

        // create the of() method
        LocalDateTime localDateTime2 = LocalDateTime.of(2019.9.8.15.8);
        System.out.println(localDateTime2);

        // getXXX()
        System.out.println(localDateTime.getDayOfWeek());

        // withXXX() sets the relevant properties. Note that a new object is returned with the same contents of the old object
        LocalDateTime newLocalDateTime = localDateTime.withDayOfMonth(20);
        System.out.println(newLocalDateTime);

        // plusXXX() adds value to attribute
        LocalDateTime newLocalDateTime2 = localDateTime.plusDays(5);
        System.out.println(newLocalDateTime2);

        // minus() reduces the value of attributes
        LocalDateTime newLocalDateTime3 = localDateTime.minusDays(3); System.out.println(newLocalDateTime3); }}Copy the code

Java 2.5. Time. Instant

public class Test {
    public static void main(String[] args) {
        // Now () creates Instant objects 8 hours slower than east 8
        Instant instant = Instant.now();
        System.out.println(instant);

        // Add a time offset
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);

        // Get the timestamp
        long millis = instant.toEpochMilli();
        System.out.println(millis);

        // Create Instant objects based on timestampsInstant instant2 = Instant.ofEpochMilli(millis); System.out.println(instant2); }}Copy the code

2.6 DateTimeFormatter

public class Test {
    public static void main(String[] args) {
        // Method 1: Predefined standard format
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        // Format: date --> string
        LocalDateTime localDateTime = LocalDateTime.now();
        String str = formatter.format(localDateTime);
        System.out.println(str);
        // Parse: string --> date
        TemporalAccessor parse = formatter.parse(str);
        System.out.println(parse);

        // Method 2: Localize related formats
        // formatstyle. LONG, formatstyle. MEDIUM, formatstyle. SHORT fits LocalDateTime
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        String str2 = formatter2.format(localDateTime);
        System.out.println(str2);

        FULL, formatstyle. LONG, formatstyle. MEDIUM, formatstyle. SHORT fits LocalDate
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter formatter3 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        String str3 = formatter3.format(localDate);
        System.out.println(str3);

        // Method 3: custom format, common
        DateTimeFormatter formatter4 = DateTimeFormatter.ofPattern("yyyy-MM-dd kk:mm:ss"); System.out.println(formatter4.format(LocalDateTime.now())); }}Copy the code

3. The comparator

Used to compare objects.

3.1 to achieve Comparable,

Create a People class to implement the Comparable interface and override the compareTo(obj) method. Returns a positive integer if the current object is greater than the comparison object obj, 0 if equal, and a negative integer if less than.

public class People implements Comparable<People> {
    private int age;
    private float height;

    @Override
    public int compareTo(People o) {
        if (this.age > o.age) {
            return 1;
        } else if (this.age == o.age) {
            return 0;
        }
        return -1;
    }

    public People(int age, float height) {
        this.age = age;
        this.height = height;
    }

    @Override
    public String toString(a) {
        return "People{" +
                "age=" + age +
                ", height=" + height +
                '} '; }}Copy the code

Arrays.sort() or collections.sort ()

public class Test {
    public static void main(String[] args) {
        People[] peoples = new People[3];
        peoples[0] = new People(18.1.7 F);
        peoples[1] = new People(20.1.8 F);
        peoples[2] = new People(14.1.5 F);
        // Array sort
        Arrays.sort(peoples);
        System.out.println(Arrays.toString(peoples));
        [People{age=14, height=1.5}, People{age=18, height=1.7}, People{age=20, height=1.8}]

        List<People> list = new ArrayList<>();
        list.add(new People(30.1.9 F));
        list.add(new People(35.1.6 F));
        list.add(new People(25.1.7 F));
        // Set sort
        Collections.sort(list);
        System.out.println(list);
        [People{age=25, height=1.7}, People{age=30, height=1.9}, People{age=35, height=1.6}]}}Copy the code

3.2 Implement classes using comparators

Write a plain People class

public class People {
    private int age;
    private float height;

    public int getAge(a) {
        return age;
    }

    public People(int age, float height) {
        this.age = age;
        this.height = height;
    }

    @Override
    public String toString(a) {
        return "People{" +
                "age=" + age +
                ", height=" + height +
                '} '; }}Copy the code

Write a test class that uses the Comparator anonymously to sort the class

public class Test {
    public static void main(String[] args) {
        People[] peoples = new People[3];
        peoples[0] = new People(18.1.7 F);
        peoples[1] = new People(20.1.8 F);
        peoples[2] = new People(14.1.5 F);
        // Array sort
        Arrays.sort(peoples, new Comparator<People>() {
            @Override
            public int compare(People o1, People o2) {
                returno1.getAge() - o2.getAge(); }}); System.out.println(Arrays.toString(peoples));[People{age=14, height=1.5}, People{age=18, height=1.7}, People{age=20, height=1.8}]

        List<People> list = new ArrayList<>();
        list.add(new People(30.1.9 F));
        list.add(new People(35.1.6 F));
        list.add(new People(25.1.7 F));
        // Set sort
        Collections.sort(list, new Comparator<People>() {
            @Override
            public int compare(People o1, People o2) {
                returno1.getAge() - o2.getAge(); }}); System.out.println(list);[People{age=25, height=1.7}, People{age=30, height=1.9}, People{age=35, height=1.6}]}}Copy the code

4. The enumeration class

4.1 Custom enumerated Classes

1. Prior to Java 5, the steps for creating enumerated classes were as follows:

public class Season {
    // 1. Modify properties with final
    private final String seasonName;
    private final String seasonDetail;

    // 2. Privatize constructor
    private Season(String seasonName, String seasonDetail) {
        this.seasonName = seasonName;
        this.seasonDetail = seasonDetail;
    }

    // 3. Provide multiple constant objects for the current enumeration class
    public static final Season SPRING = new Season("Spring"."Spring Blossoms");
    public static final Season SUMMER = new Season("Summer"."The sun is burning.");
    public static final Season AUTUMN = new Season("Autumn"."Crisp autumn air");
    public static final Season WINTER = new Season("Winter"."Ice and Snow");

    // 4. Provide methods to get attributes
    public String getSeasonName(a) {
        return seasonName;
    }

    public String getSeasonDetail(a) {
        return seasonDetail;
    }

    @Override
    public String toString(a) {
        return "Season{" +
                "seasonName='" + seasonName + '\' ' +
                ", seasonDetail='" + seasonDetail + '\' ' +
                '} '; }}Copy the code

2, the test effect is as follows:

public class Test {
    public static void main(String[] args) {
        Season spring = Season.SPRING;
        System.out.println(spring);
        SeasonName = seasonName, seasonDetail= seasonDetail}}}Copy the code

4.2 Using the enum keyword

Java 5 introduces the enum keyword, which is used to define enumerated classes

// Enumeration classes defined with this keyword inherit from java.lang.enum
public enum Season {
    // Provide the object of the current enumeration class, placed at the beginning
    SPRING("Spring"."Spring Blossoms"),
    SUMMER("Summer"."The sun is burning."),
    AUTUMN("Autumn"."Crisp autumn air"),
    WINTER("Winter"."Ice and Snow");

    private final String SeasonName;
    private finalString SeasonDetail; Season(String seasonName, String seasonDetail) { SeasonName = seasonName; SeasonDetail = seasonDetail; }}Copy the code

2, the test effect and the common methods of Enum class are as follows

public class Test {
    public static void main(String[] args) {
        Season spring = Season.SPRING;
        System.out.println(spring);         / / output SPRING

        // Enum values() method
        Season[] values = Season.values();  // Returns all objects of the enumerated class
        for (Season s : values) {
            System.out.println(s);
        }
        // Enum valueOf() method
        Season winter = Season.valueOf("WINTER"); // Gets the specific object of the enumeration class based on the object nameSystem.out.println(winter); }}Copy the code

3. The situation when implementing an interface

For example, if you have an interface like this, you can override methods in the class as well as in the object if the enumerated class implements the interface

public interface Info {
    void show(a);
}
Copy the code
public enum Season implements Info {
    // Override a method in an object, and each object outputs something different
    SPRING("Spring"."Spring Blossoms") {
        @Override
        public void show(a) {
            System.out.println("It's spring.");
        }
    },
    SUMMER("Summer"."The sun is burning.") {
        @Override
        public void show(a) {
            System.out.println("It's summer.");
        }
    },
    AUTUMN("Autumn"."Crisp autumn air") {
        @Override
        public void show(a) {
            System.out.println("This is autumn.");
        }
    },
    WINTER("Winter"."Ice and Snow") {
        @Override
        public void show(a) {
            System.out.println("It's winter."); }};private final String SeasonName;
    private final String SeasonDetail;

    Season(String seasonName, String seasonDetail) {
        SeasonName = seasonName;
        SeasonDetail = seasonDetail;
    }

// If you override the interface's methods in a class, each object will output the same thing
// @Override
// public void show() {
// system.out.println (" This is a season "); // system.out.println (" this is a season ");
/ /}
}
Copy the code
public class Test {
    public static void main(String[] args) {
        Season spring = Season.SPRING;
        spring.show(); // It is spring

        Season winter = Season.valueOf("WINTER");
        winter.show(); // It is winter}}Copy the code