Commonly used classes in java (Object, String, Math, Date)


Commonly used classes in java (Object, String, Math, Date)


1. Object class and its methods

The object class is the base class and super class of all classes, the direct or indirect parent of all classes, and is located at the top of the inheritance tree.

Any class that does not write "extends" to indicate that it inherits a certain class will directly inherit the object class by default, otherwise it will be indirect inheritance.

The methods defined by the object class are methods that all objects have.
The object class can store any object.

1. getClass() method

Returns the actual object type stored in the application Application
: Usually used to determine whether the actual object types stored in two references are consistent.

2. hashCode() method

public int hashCode(){}
returns the hash code value of the object.
The hash value is an int type value calculated using the hash algorithm based on the object's address or string or number.
Generally, the same object returns the same hash code .

3. toString method

public String toString(){}
returns the string representation (expression) of the object.
This method can be overridden according to program needs, such as: displaying the properties of the object

4. equals() method

The default implementation of public Boolean equals(object obj){}
is (this == obj) , which compares whether the addresses of two objects are the same
. It can be overridden and compares whether the contents of the two objects are the same.

"==" compares whether both sides are the same. If it is a basic type, it means the value is the same . If it is a reference type, it means the address is equal, that is, the same object . ,

The default equals() method is the same as "==". [The same object address indicates the same object, and the hashcode is the same]

The default of equals() is to compare two objects and hashcode (hash code). However, you can override the equals() method according to your own requirements. [Generally rewritten as whether the contents of the comparison objects are the same]

  • equals() method override step

Compare whether two references point to the same pair phenomenon [obj == this]
Determine whether two obj are null [obj == null]
Determine whether the actual object types pointed to by the two references are consistent [obj instanceof xx]
Force type conversion
and compare Whether the values ​​of each attribute are the same

public class User {
    
    
	
	String name;
	Integer id;
	
	@Override
	public boolean equals(Object obj) {
    
    
		// 首先判断传进来的obj是否是调用equals方法对象的this本身,提高判断效率
		if (obj == this) {
    
    return true;}
		// 判断传进来的obj是否是null,提高判断效率
		if (obj == null) {
    
    return false;}
		// 判断传进来的obj是否是User对象,防止出现类型转换的异常
		if (obj instanceof User) {
    
    
			User user = (User) obj;
			boolean flag = this.name.equals(user.name) && this.id == user.id;
			return flag;
		}
		// 如果没有走类型判断语句说明两个比较的对象它们的类型都不一样,结果就是false了
		return false;
	}	
     ....//get\set 方法
}

5. finalize() method

  • When an object is determined to be a garbage object, this method is automatically called by the JVM to mark the object and enter the recycling queue.
  • Garbage object: There is no valid reference pointing to this object , so it is a garbage object. 【new xxx(…);】
  • Garbage collection: GC destroys objects and releases storage space
  • Automatic recycling mechanism: When the JVM memory is exhausted, all garbage objects are recycled at once
  • Manual recycling mechanism: Use System.gc(); to notify the JVM to perform garbage collection.

2. String class

1. Attention

Strings are constants and cannot be changed after creation.

The literal value of the string is stored in the string pool and can be shared.

String s = "Hello", create an object and store it in the string pool.

String s = new String("Hello") creates two objects, one in the heap and one in the pool.

The principle is as follows:
Insert image description here
Insert image description here

  @Test
    public void StringTest() {
    
    
        String str = "abc";
        String str2 = new String("abcd");
        System.out.println("str2:"+str2.hashCode());

        str2 = "abc";
        //存在方法区  字符串常量池中 可以共享 str 和str2 相同(引用指向同一内容)
        System.out.println("str:" + str.hashCode());
        System.out.println("str2 : " + str2.hashCode());
        System.out.println(str.equals(str2));
        System.out.println("--------------");
        // String不可变,赋给不同值,对象改变了,引用指向了另外的内容
        str = "abcd";
        System.out.println("str:" + str.hashCode());

        System.out.println(str.equals(str2));
    }
str2:2987074
str:96354
str2 : 96354
true
--------------
str:2987074
false

Process finished with exit code 0

2. Commonly used methods

Length, get the specified subscript, convert to array, whether it contains str(t or f), match the first subscript, match the last subscript, remove the spaces before and after the string, and convert lowercase to uppercase. Determine whether the string ends with xx, replace the old string with a new string (new object), and split based on str.

  • public int length(): Returns the length of the string.

  • public char charAt(int index): Get a string based on the subscript

  • public char[] toCharArray(): Convert a string into an array.

  • public boolean contains (String str): Determine whether the current string contains str.

  • public int index0f (String str): Find the first occurrence of the subscript of str. If it exists, return the subscript; if it does not exist, return -1.

  • public int lastIndex0f (String str): Find the subscript index of the last occurrence of a string in the current string.

  • public String trim(): Remove spaces before and after the string.

  • public String toUpperCase (): Convert lowercase to uppercase.

  • public boolean endWith (String str): Determine whether the string ends with str.

  • public String replace (char oldChar, char newChar); Replace the old string with the new string

  • public String[] split (String str): split based on str.

3. Extension

StringBuilder 和 StringBuffer

They are all final modifications and cannot be modified. They are mutable because of the use of the append and insert methods. The returned object is the same
StringBuffer: a variable-length string, provided by JDK1.0, which has slow operation efficiency and thread safety. (Suitable for multi-threading)
StringBuilder: Variable-length string, provided by JDK5. 0, fast running efficiency and thread-unsafe. (Suitable for single thread)
But they are more efficient than String class.

  • StringBuilder
    The difference between the String class and the StringBuilder class: The content of the String class is fixed, while the content of the StringBuilder class is variable.
    StringBuilder is faster than StringBuffer when the string buffer is used by a single thread.
    The main operations are the append and insert methods .

For example, if z refers to a generator object whose current content is "start", then the method call z.append("le") will cause the string generator to contain "startle", while z.insert(4
, "le") will change the string generator to include "starlet".

  • StringBuffer
    can change the length and content of the sequence through certain method calls.
    String buffers can be used safely by multiple threads. These methods can be synchronized when necessary, so that all operations on any particular instance appear to occur in a serial order consistent with the order of method calls made by each thread involved.
    The main operations are the append and insert methods

For example, if z refers to a string buffer object whose current content is "start", then this method call z.append("le") will cause the string buffer to contain "startle", while z.insert(4, " le") will change the string buffer to contain "starlet".

4.Reference materials

https://blog.csdn.net/weixin_43502661/article/details/88781050
https://blog.csdn.net/xiaosao_/article/details/126278199
https://blog.csdn.net/qq_59212867/article/details/125119222

3. Math

The Math class contains static methods for performing basic mathematical operations, such as elementary exponentials, logarithms, square roots, and trigonometric functions.

1 Commonly used functions

  • Math.PI recorded pi
  • Math.E records the constant of e
  • There are some similar constants in Math, which are commonly used quantities in engineering mathematics.
  • Math.abs find absolute value
  • Math.sin sine function Math.asin arcsine function
  • Math.cos cosine function Math.acos inverse cosine function
  • Math.tan tangent function Math.atan arctangent function Math.atan2 arctangent function of quotient
  • Math.toDegrees Convert radians to angles Math.toRadians Convert angles to radians
  • Math.ceil gets the largest integer that is not less than a certain number
  • Math.floor gets the largest integer not greater than a certain number
  • Math.IEEEremainder
  • Math.max finds the largest of two numbers
  • Math.min finds the smallest of two numbers
  • Math.sqrt Find the square root
  • Math.pow finds any power of a number and throws ArithmeticException to handle overflow exceptions.
  • Math.exp finds any power of e
  • Math.log10 base 10 logarithm
  • Math.log natural logarithm
  • Math.rint finds the nearest integer double to a certain number (it may be larger or smaller than a certain number)
  • Math.round is the same as above, returning int type or long type (the previous function returned double type)
  • Math.random returns a random number between 0 and 1 [0, 1)

2 References

https://blog.csdn.net/I_r_o_n_M_a_n/article/details/118864693

4. Date

1 Relevant knowledge

The Date class encapsulates the current date and time, and we can use this class to manipulate time and date. Before using this class, we need to import the java.util.Date class.

The Date class provides two constructors to instantiate Date objects:

Initialize the object using the current date and time;

  • Date date = new Date();

The second constructor receives a parameter, which is the number of milliseconds since January 1, 1970.

  • Date date1 = new Date(1581997363000L).

2 Some common methods of Date

method describe
boolean after(Date date) Returns true if the Date object on which this method is called is after the specified date, otherwise it returns false.
boolean before(Date date) Returns true if the Date object on which this method is called is before the specified date, otherwise it returns false.
Object clone( ) Returns a copy of this object.
int compareTo(Date date) Compares the Date object and the specified date when this method is called. When the two are equal, 0 is returned. If the calling object is before the specified date, a negative number is returned. The calling object returns a positive number after the specified date.
boolean equals(Object date) Returns true when the Date object calling this method is equal to the specified date, otherwise it returns false.
long getTime( ) Returns the number of milliseconds represented by this Date object since January 1, 1970 00:00:00 GMT.
void setTime(long time) Set the time and date in time milliseconds since January 1, 1970 00:00:00 GMT.
String toString( ) Converts a Date object to a String representation and returns the string.

3 Calendar related classes (Calendar)

The Calendar class is an abstract class that provides methods for manipulating calendar fields (such as getting next week's date). An instant can be expressed as a millisecond value, which is the offset from the epoch (00:00:00.000 January 1, 1970 GMT, Gregorian calendar).

4 References

https://blog.csdn.net/m0_59854777/article/details/119564546

Guess you like

Origin blog.csdn.net/weixin_44625361/article/details/127585481