Common classes based on javase

Common classes based on javase

preface
This article will introduce:

  • String related classes and common methods: String class, StringBuffer class and String Builder class
  • Date class
  • Math class
  • Random class
  • System class
  • Biglnteger class
  • BigDecimal class

String class
String is a final class that represents an immutable character sequence
Instantiation method of String:
1: By literal definition.
2: Through the new + constructor
explain:
Through literal definition: at this time, the data of s1 and s2 are 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 are the corresponding address values after the data opens up space in the heap space.
String s3=new String("javaEE");
String s4=new String("javaEE");
Memory structure analysis
Common methods of String class:
The length of the returned string: return value length

int length()

Returns the character at an index. return value[index]

char charAt(int index)

Judge whether it is an empty string: return value length==0

boolean isEmpty()

Compare whether the contents of the string are the same

 Boolean equals(Object obj)

Compare the size of two strings

int compareTo(String anotherString)

Returns a string. It is intercepted from beginIndex of this string and included in the previous bit of endIndex.

String substring(int beginIndex,int endIndex)

Returns a new string, which is intercepted from beginIndex

String substring(int beginIndex)

toggle case

 String toLowerCase():Using the default locale, the string Convert all characters in to lowercase
 String toUpperCase(): Using the default locale, the string Convert all characters in to uppercase

String and basic data conversion
String -- > basic data type, wrapper class
public static int parseInt(String s) of Integer wrapper class: you can convert a string composed of "number" characters into an Integer.
Similarly, use Java The Byte, Short, Long, Float and Double classes in Lang package are called accordingly
The class method of can convert the string composed of "number" characters into the corresponding basic data type.
Basic data type, packing class - > string
Call public String valueOf(int n) of String class to convert int type to String
Corresponding valueOf(byte b), valueOf(long l), valueOf(float f)
valueOf(double d) and valueOf(boolean b) can be converted from the corresponding type of parameter to string
Conversion between String and character array
Character array -- > string
Constructor of String class: String(char []) and String(char []), int offset, int
length) creates a string object with all and part of the characters in the character array, respectively.
String - > character array
public char[] toCharArray(): store all characters in the string in a character array
Methods in.
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): provides a method to store strings within the specified index range into an array.

StringBuffer class

  • java.lang.StringBuffer represents variable character sequence, jdk1 0, the string content can be added or deleted, and no new object will be generated at this time.

  • Many methods are the same as String.

  • When passed as a parameter, the value can be changed inside the method.

Instantiation mode
The StringBuffer class is different from String, and its object must be generated using a constructor. There are three constructors:
StringBuffer(): a string buffer with an initial capacity of 16
StringBuffer(int size): construct a string buffer with a specified capacity
StringBuffer(String str): initializes the content to the specified string content

StringBuffer common methods
Many append() methods are provided for string splicing

StringBuffer append(xxx)

Delete the contents of the specified location

StringBuffer delete(int start,int end)

Replace the [start,end) position with str

StringBuffer replace(int start, int end, String str)

Insert xxx at the specified location

StringBuffer insert(int offset, xxx)

Reverse the current character sequence

StringBuffer reverse()

explain:

  • When append and insert, if the original value array is not long enough, it can be expanded
  • The above methods support method chain operation
  • Method chain principle
@Override
public StringBuffer append(String str)
{
	super.append(str);
	return this;
} 

StringBuilder class
StringBuilder is jdk5 0 added.
StringBuilder and StringBuffer are very similar. They both represent variable character sequences,
The method of providing relevant functions is the same.
The methods defined in StringBuffer are all synchronized. So thread safety.

Interview question: compare String, StringBuffer and StringBuilder

String(JDK1.0): Immutable character sequence
StringBuffer(JDK1.0): Variable character sequence, low efficiency, thread safety
StringBuilder(JDK 5.0): Variable character sequence, high efficiency and unsafe thread
 Note: if it is passed as a parameter, the method is internal String Does not change its value,
StringBuffer and StringBuilder Will change its value

Time spent executing the same piece of code
SringBuilder<StringBuffer<String

Date class

java.util.Date class
Subclass: Java sql. Date
Use of two constructors:
Constructor 1: Date(): the object created by the parameterless constructor can obtain the local current time.

   Date date = new Date();

Constructor 2: Date(long date) creates a Date object with a specified number of milliseconds

  Date date2= new Date(1623051026736L);
  //Specified number of milliseconds: refers to the time from 00:00:00 on January 1, 1970.

common method

 -->toString(): Displays the current year, month, day, hour, minute and second
 -->getTime():Get current Date The timestamp corresponding to the object.
  //Returns the time difference in milliseconds between the current time and 0:0:0:0 on January 1, 1970.
  //This is called a timestamp
  -->int getYear()  Gain year
  -->int getMOnth()  Gain month
  ...........

java.text.SimpleDateFormat class
Allow formatting: date – > text
Parse: text - > date
format:

SimpleDateFormat() : Create objects in the default schema and locale
 public SimpleDateFormat(String pattern): The construction method can use parameters pattern
 Creates an object in the specified format that calls:
public String format(Date date): Method to format a time object date

analysis

public Date parse(String source): Parses text from the beginning of a given string to generate
 A date.

java. util. Calendar Class
Calendar is an abstract base class, which is mainly used to complete the mutual operation between date fields.
Method to get Calendar instance

  • Use calendar Getinstance() method
  • Call the constructor of its subclass GregorianCalendar.

Demonstration of common methods

 //2. Common methods
     //get()
      int days = calendar.get(Calendar.DAY_OF_MONTH);
        //What day of the month is the current time
      System.out.println(days);
     System.out.println(Calendar.DAY_OF_YEAR);

      //set()
     calendar.set(Calendar.DAY_OF_MONTH,22);
     //void type. The change is the object itself
    System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//22

        //add()
  calendar.add(Calendar.DAY_OF_MONTH,-3);//void
   System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//19

        //getTime(): Calendar Class -- > date
     Date date = calendar.getTime();
     System.out.println(date);
     //Settime(): date -- > Calendar Class
    Date date1=new Date();
    calendar.setTime(date1);
    System.out.println(date1);

System class

void gc(): this method is used 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 execution of the system.
String getProperty(String key): this method is used to obtain the value corresponding to the property named key in the system.
The common attribute names and functions in the system are shown in the following table:

Math class

java.lang.Math A series of static methods are provided for scientific calculation. The parameters and return of its method
 The value type is generally double Type.
abs absolute value
acos,asin,atan,cos,sin,tan trigonometric function
sqrt square root
pow(double a,doble b) a of b pow 
log Natural logarithm
exp e Bottom index
max(double a,double b)
min(double a,double b)
random() Return 0.0 To 1.0 Random number of
long round(double a) double Type data a Convert to long Type (rounded)
toDegrees(double angrad) Radian ->angle
toRadians(double angdeg) Angle ->radian

Biglnteger class

java. The BigInteger of the math package can represent an immutable integer of arbitrary precision.
BigInteger provides the counterparts of all Java's basic integer operators and Java All relevant methods of lang.math.
In addition, BigInteger provides the following operations: modular arithmetic, GCD calculation, prime test, prime generation, bit operation, and some other operations
constructor

BigInteger(String val): Build from string BigInteger object

common method

public BigInteger abs(): 
Return to this BigInteger Absolute value of BigInteger.  
BigInteger add(BigInteger val) : 
The return value is (this + val) of BigInteger
BigInteger subtract(BigInteger val) : 
The return value is (this - val) of BigInteger
BigInteger multiply(BigInteger val) : 
The return value is (this * val) of BigInteger
BigInteger divide(BigInteger val) : 
The return value is (this / val) of BigInteger. Integer division preserves only the integer part.  
BigInteger remainder(BigInteger val) : 
The return value is (this % val) of BigInteger. 
BigInteger[] divideAndRemainder(BigInteger val): 
Return contains (this / val) Heel(this % val) Two of BigInteger Array of.
 BigInteger pow(int exponent) : 
 The return value is (thisexponent) of BigInteger. 

BigDecimal class

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

constructor
public BigDecimal(double val)
public BigDecimal(String val)

Common methods are similar to the Biglnteger class. You can change the parameter name.

last

Paste several algorithm problems

  1. Simulate a trim method to remove the spaces at both ends of the string.

  2. Inverts a string. Inverts the specified part of the string. For example, "abcdefg" is reversed to "abfedcg"

  3. Gets the number of occurrences of one string in another string.
    For example, get the number of occurrences of "ab" in "abkkcadkabkebfkabkskab"

4. Get the largest identical substring in the two strings. For example:
str1 = "abcwerthelloyuiodef";str2 = "cvhellobnm"
Tip: compare the short string with the substring whose length decreases in turn with the longer string.

5. Sort the characters in the string in natural order.
Tips:
1) The string becomes an array of characters.
2) Sort the array, select, bubble, arrays sort();
3) Turns the sorted array into a string.

Keywords: Java

Added by paul.mac on Mon, 31 Jan 2022 23:38:03 +0200