[Java advanced programming] Java common classes

insert image description here

1. String-related classes

1.1. String-related classes: String

  • String is declared final and cannot be inherited
  • String implements the Serializable interface: indicates that the string supports serialization; implements the Comparable interface: indicates that the String can be compared in size
  • String internally defines final char[] value for storing string data
  • String: Represents an immutable sequence of characters. Short name: immutability.
    • 1. When reassigning a string, you need to reassign the memory area, and you cannot use the original value for assignment.
    • 2. When performing concatenation operations on existing strings, it is also necessary to re-specify the memory area for assignment, and the original value cannot be used for assignment
    • 3. When calling the replace() method of String to modify the specified character or string, it is also necessary to re-specify the memory area for assignment, and the original value cannot be used for assignment
  • Assign a value to a string in a literal way (different from new), and the string at this time is declared in the string constant pool
  • Strings with the same content will not be stored in the string constant pool
/**
 *  String的实例化方式
 *  方式一:通过字面量定义的方式
 *  方式二:通过new + 构造器的方式
 *
 *  面试题:String s = new String("abc");方式创建对象,在内存中创建了几个对象?
 *  答:两个:一个是堆空间中new结构,另一个是char[]对应的常量池中的数据:"abc"
 */
@Test
public void test() {
    // 通过字面量定义的方式:此时的s1和s2的数据javaEE声明在方法区中的字符串常量池中。
    String s1 = "javaEE";
    String s2 = "javaEE";
    // 通过new + 构造器的方式:此时的s3和s4保存的地址值,是数据在堆空间中开辟空间以后对应的地址值
    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
};
  • The splicing result of constants and constants is in the constant pool. And there will not be constants with the same content in the constant pool.
  • As long as one of them is a variable, the result is on the heap.
  • If the splicing result is to call the intern() method, the return value is in the constant pool
String s1 = "hello";
String s2 = "world";
String s3 = "hello" + "world";
String s4 = s1 + "world";
String s5 = s1 + s2;
String s6 = (s1 + s2).intern();
final String s7 = "hello"; // 此时的s7是一个常量
String s8 = s7 + "world";

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

1.2. String-related classes: common methods of String

  • int length(): returns the length of the string: return value.length
  • char charAt(int index): returns the character at an index return value[index]
  • boolean isEmpty(): Determine whether it is an empty string: return value.length == 0
  • String toLowerCase(): Use the default locale to convert all characters in String to lowercase
  • String toUpperCase(): Use the default locale to convert all characters in String to uppercase
  • String trim(): returns a copy of the string, ignoring leading and trailing blanks
  • boolean equals(Object obj): compares whether the contents of the strings are the same
  • boolean equalsIgnoreCase(String anotherString): similar to the equals method, ignoring case
  • String concat(String str): Concatenates the specified string to the end of this string. Equivalent to using "+"
  • int compareTo(String anotherString): Compare the size of two strings
  • String substring(int beginIndex): returns a new string, which is a substring intercepted from beginIndex to the end of this string
  • String substring(int beginIndex, int endIndex): returns a new string, which is a substring of this string intercepted from beginIndex to endIndex (not included)
  • boolean endsWith(String suffix): Tests whether this string ends with the specified suffix
  • boolean startsWith(String prefix): Tests whether this string starts with the specified prefix
  • boolean startsWith(String prefix, int toffset): Tests whether the substring of this string starting at the specified index starts with the specified prefix
  • boolean contains(CharSequence s): Returns true if and only if this string contains the specified sequence of char values
  • int indexOf(String str): Returns the index of the first occurrence of the specified substring in this string
  • int indexOf(String str, int fromIndex): Returns the index of the first occurrence of the specified substring in this string, starting from the specified index
  • int lastIndexOf(String str): Returns the index of the rightmost occurrence of the specified substring in this string
  • int lastIndexOf(String str, int fromIndex): Returns the index of the last occurrence of the specified substring in this string, starting the reverse search from the specified index
  • String replace(char oldChar, char new Char): returns a new string obtained by replacing all occurrences of oldChar in this string with newChar
  • String replace(CharSequence target, CharSequence replacement): Replaces all substrings of this string that match the literal target sequence with the specified literal replacement sequence
  • String replaceAll(String regex, String replacement): Use the given replacement to replace all substrings of this string that match the given regular expression
  • String replaceFirst(String regex, String replacement): Replaces the first substring of this string matching the given regular expression with the given replacement
  • boolean matches(String regex): tells whether this string matches the given regular expression
  • String[] split(String regex): Splits this string based on matches of the given regular expression
  • String[] split(String regex, int limit): split the string according to the given regular expression, up to the limit. If it exceeds, all the rest will be placed in the last element

1.3. Conversion between String and basic data types and wrapper classes

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

1.4. Conversion between String and char[]

  • String --> char[]: call String's toCharArray()
  • char[] --> String: Call the constructor of String

1.5. Conversion between String and byte[]

  • String --> byte[]: Call String's getBytes()
  • byte[] --> String: Call the constructor of String

1.6. What are the similarities and differences between String, StringBuffer, and StringBuilder?

  • String: an immutable sequence of characters; the bottom layer is stored using final char[]
  • StringBuffer: variable character sequence; thread-safe, low efficiency; underlying storage using char[]
  • StringBuilder: variable character sequence; newly added in JDK 5.0, thread unsafe, high efficiency; bottom layer uses char[] storage

1.7, StringBuffer source code analysis

  • Expansion problem: If the underlying array of data to be added cannot hold, then the underlying array needs to be expanded. By default, the expansion is 2 times the original capacity + 2, and the elements in the original array are copied to the new array at the same time
  • Guiding significance: During development, it is recommended that you use: StringBuffer(int capacity) or StringBuilder(int capacity)
String str = new String(); // char[] value = new char[0];
String str1 = new String("abc"); // char[] value = new char[]{'a','c','c'};

StringBuffer sb1 = new StringBuffer(); // char[] value = new char[16];底层创建了一个长度是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];

1.8. Common methods of StringBuffer class

  • StringBuffer append(xxx): Provides many append() methods for string concatenation
  • StringBuffer delete(int start, int end): delete the content at the specified location
  • StringBuffer replace(int start, int end, String str): Replace the [start, end) position with str
  • StringBuffer insert(int offset, xxx): Insert xxx at the specified position
  • StringBuffer reverse(): reverse the current character sequence

1.9. Comparing the efficiency of String, StringBuffer and StringBuilder

  • Arrange from high to low: StringBuilder > StringBuffer > String

1.10, conversion between String and StringBuffer, StringBuilder

  • String --> StringBufferr, StringBuilder: call StringBuffer, StringBuilder constructor
  • StringBufferr、StringBuilder --> String:
    • Call the String constructor
    • StringBuffer、StringBuilder的toString()

2. Date and time API before JDK 8

2.1, java.lang.System class

  • The public static long currentTimeMillis() provided by the System class is used to return the time difference in milliseconds between the current time and January 1, 1970 at 0:00:00.

2.2, java.util.Date class

  • Represents a specific instant, accurate to milliseconds
  • Constructor:
    • Date(): Objects created with a no-argument constructor can get the local current time
    • Date(long date)
  • common method
    • getTime(): Returns the number of milliseconds this Date object represents since January 1, 1970 00:00:00 GMT
    • toString(): Convert this Date object to a String of the following form: dow mon dd hh:mm:ss zzz yyyy

2.3、java.text.SimpleDateFormat类

  • The API of the Date class is not easy to internationalize and is largely deprecated. The java.text.SimpleDateFormat class is a concrete class for formatting and parsing dates in a locale-independent manner.
  • format:
    • SimpleDateFormat(): default schema and locale creation object
    • public SimpleDateFormat(String pattern): This constructor can create an object in the format specified by the parameter pattern
    • public String format(Date date): format time object date
  • Parse:
    • public Date parse(String source): Parses the text from the beginning of the given string to generate a date

2.4, java.util.Calendar class

  • Calendar is an abstract base class, mainly used to complete the function of interoperability between date fields
  • Method to get Calendar instance
    • Use the Calendar.getInstance() method
    • Call the constructor of its subclass GregorianCalendar
  • An instance of Calendar is an abstract representation of system time, and the desired time information can be obtained through the get(int field) method. For example, YEAR, MONTH, DAY_OF_WEEK, HOUR_OF_DAY, MINUTE, SECOND
    • public void set(int field, int value)
    • public void add(int field, int amount)
    • public final Date getTime()
    • public final void setTime(Date date)
  • Notice
    • When getting the month: January is 0, February is 1, and so on, December is 11
    • When getting the week: Sunday is 1, Monday is 2, and so on, Saturday is 7

3. New date and time API in JDK 8

3.1. Reasons for the appearance of the new date and time API

  • Mutability: classes like dates and times should be immutable
  • Offset: The year in Date starts from 1900, and the month starts from 0
  • Formatting: Formatting is only useful for Date, not for Calender
  • Also, none of them are thread-safe; can't handle leap seconds etc.

3.2, LocalDate, LocalTime, LocalDateTime class

  • Instances of them are immutable objects representing date, time, date and time, respectively, using the ISO-8601 calendar system.
  • Creation method:
    • now() / now(ZoneId zone): Static method, create an object/object of the specified time zone according to the current time
    • of(): static method, creates an object according to the specified date/time
  • The method of the get class:
    • getDayOfMonth()/getDayOfYear(): Get the number of days in the month (1-31)/get the number of days in the year (1-366)
    • getDayOfWeek(): Get the day of the week (returns a DayOfWeek enumeration value)
    • getMonth(): Get the month and return a Month enumeration value
    • getMonthValue()/getYear(): get the month (1-12)/get the year
    • getHour()/getMinute()/getSecond(): Get the hour, minute, and second corresponding to the current object
  • The method of the set class:
    • withDayOfMonth()/withDayOfYear()/withMonth()/withYear(): Modify the number of days in the month, the number of days in the year, the month, and the year to the specified value and return a new object
  • The method of the operation class:
    • plusDays()/plusWeeks()/plusMonths()/plusYears()/plusHours(): Add days, weeks, months, years, hours to the current object
    • minusMonths()/minusWeeks()/minusDays()/minusYears()/minusHours(): Subtract months, weeks, days, years, hours from the current object

3.3. Instantaneous: Instant

  • An instant on the timeline, likewise in Java since 1970, but in milliseconds
  • Common methods:
    • now(): static method, returns the object of the Instant class in the default UTC time zone
    • ofEpochMilli(long epochMilli): static method, returns an object of the Instant class based on 1970-01-01 00:00:00 plus the specified number of milliseconds
    • atOffset(ZoneOffset offset): Combines the immediate offset to create an OffsetDateTime
    • toEpochMilli(): returns the number of milliseconds from 1970-01-01 00:00:00 to the current time, which is the timestamp

3.4、java.time.format.DateTimeFormatter class

  • Predefined standard formats. Such as: ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
  • Localization-dependent formatting. Such as ofLocalizedDateTime(FormatStyle.LONG)
  • custom format. Such as: ofPattern("yyyy-MM-dd hh:mm:ss E")
  • Common methods:
    • ofPattern(String pattern): static method, returns a DateTimeFormatter specifying the string format
    • format(TemporalAccessor t): format a date, time, and return a string
    • parse(CharSequence test): parses a character sequence in the specified format into a date and time

4. Java Comparator

4.1. Method 1: Natural arrangement: java.lang.Comparable

  • The Comparable interface enforces an overall ordering of the objects of each class that implements it. This ordering is called the natural ordering of classes
  • The class that implements Comparable must implement the compareTo(Object obj) method, and the two objects are compared by the return value of the compareTo(Object obj) method.
    • Returns a positive integer if the current object this is greater than the formal parameter object obj
    • If the current object this is less than the formal parameter object obj, return a negative integer
    • Returns zero if the current object this is equal to the formal parameter object obj
  • Lists (and arrays) of objects implementing the Comparable interface can be automatically sorted via Collections.sort or Arrays.sort.

4.2. Method 2: Custom sorting: java.util.Comparator

  • When the element type does not implement the java.lang.Comparable interface and it is inconvenient to modify the code, or the sorting rule that implements the java.lang.Comparable interface is not suitable for the current operation, then you can consider using the Comparator object to sort
  • Override the compare(Object o1, Object o2) method to compare the size of o1 and o2
    • If the method returns a positive integer, it means that o1 is greater than o2
    • If the method returns 0, it means equality
    • Returns a negative integer, indicating that o1 is less than o2
  • A Comparator can be passed to a sort method (such as Collections.sort or Arrays.sort), allowing precise control over the sort order

5. System class

  • The System class represents the system, and many attributes and control methods at the system level are placed inside this class.
  • Member variables:
    • in: standard input stream (keyboard input)
    • out: standard output stream (monitor)
    • err: standard error output stream (monitor)
  • Member method:
    • native long currentTimeMillis(): The function of this method is to return the current computer time. The expression format of the time is the milliseconds of the difference between the current computer time and GMT time (Greenwich Mean Time) on January 1, 1970 at 0:00:00 number.
    • void exit(int status): The function of this method is to exit the program. The value of status is 0 for normal exit, and non-zero for abnormal exit.
    • void gc(): The function of this method is to request the system to perform garbage collection. As for whether the system recycles immediately, it depends on the implementation of the garbage collection algorithm in the system and the situation when the system is executed.
    • String getProperty(String key): The function of this method is to obtain the value corresponding to the property whose property name is key in the system.
      • java.version: java runtime environment version
      • java.home: java installation directory
      • os.name: the name of the operating system
      • os.version: version of the operating system
      • user.name: the user's account name
      • user.home: the user's home directory
      • user.dir: the user's current working directory

6. Math class

  • abs: absolute value
  • acos, asin, atan, cos, sin, tan: trigonometric functions
  • sqrt: square root
  • pow(double a, double b): b power of a
  • log: natural logarithm
  • exp: e is the base exponent
  • max(double a, double b)
  • min(double a, double b)
  • random(): returns a random number from 0.0 to 1.0
  • long round(double a): Double type data a is converted to long type (rounded)
  • toDegrees(double angrad): radians –> angles
  • toRadians(double angdeg): angle –> radians

7. BigInteger and BigDecimal

7.1 BigInteger class

  • The BigInteger of the java.math package can represent immutable arbitrary-precision integers
  • Constructor:
    • BigInteger(String val): Build a BigInteger object from a string
  • Common methods:
    • public BigInteger abs(): Returns the BigInteger of the absolute value of this BigInteger
    • BigInteger add(BigInteger val): returns a BigInteger whose value is (this+val)
    • BigInteger subtract(BigInteger val): returns a BigInteger whose value is (this-val)
    • BigInteger multiply(BigInteger val): returns a BigInteger whose value is (this*val)
    • BigInteger divide(BigInteger val): Returns a BigInteger whose value is (this/val). Integer division keeps only the integer part
    • BigInteger remainder(BigInteger val): Returns a BigInteger whose value is (this%val)
    • BigInteger[] divideAndRemainder(BigInteger val): Returns an array of two BigIntegers containing (this/val) followed by (this%val)
    • BigInteger pow(int exponent): Returns a BigInteger whose value is (this to the power of exponent)

7.2 BigDecimal class

  • The BigDecimal class supports immutable, arbitrary-precision signed decimal fixed-point numbers
  • Constructor:
    • public BigDecimal(double val)
    • public BigDecimal(String val)
  • Common methods:
    • public BigDecimal add(BigDecimal adding)
    • public BigDecimal subtract(BigDecimal subtrahend)
    • public BigDecimal multiply(BigDecimal multiplicand)
    • public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)

Guess you like

Origin blog.csdn.net/qq_51808107/article/details/131443038