Object class
Object()
Constructor.
@HotSpotIntrinsicCandidate public Object() {}
@HotSpotIntrinsicCandidate is an annotation, which will be skipped temporarily and summarized later.
Returns the runtime class of this Object. The returned class Object is the Object locked by the static synchronized method representing the class. The final keyword prevents subclasses that inherit the Object class from overriding the method.
getClass()
Returns the runtime class of this Object. The returned class Object is the Object locked by the static synchronized method representing the class. The final keyword prevents subclasses that inherit the Object class from overriding the method.
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
hashCode()
hash extension
Hash, which is generally translated as hash, hash, or transliterated into hash, is to transform the input of any length (also known as pre mapping pre image) into the output of fixed length through hash algorithm, and the output is the hash value. This transformation is a compression mapping, that is, the space of hash value is usually much smaller than that of input. Different inputs may be hashed into the same output, so it is impossible to determine the unique input value from the hash value. In short, it is a function that compresses messages of any length to a message digest of a fixed length.
For example, if you want to store 100 different data, you need to compare it with 99, which is inefficient. However, if I provide 10 hash tables to store 10 numbers from 0 to 9, first calculate which hash table the 100th number is in, and then go to the corresponding hash table to find it.
@HotSpotIntrinsicCandidate public native int hashCode();
Returns the hash code value of the object. This method is supported for hash tables, as provided by HashMap. The hash value may be the same for different objects.
equals()
To determine whether two classes are equal, many classes will override this method. It can be seen that in the Object class, the comparison is whether the references are equal, not whether the values are equal.
public boolean equals(Object obj) { return (this == obj); }
clone()
Copy the same class
@HotSpotIntrinsicCandidate protected native Object clone() throws CloneNotSupportedException;
The original intention of the new operator is to allocate memory. When the program executes the new operator, first look at the type behind the new operator, because only when you know the type can you know how much memory space to allocate. After the memory is allocated, the constructor is called to fill the fields of the object. This step is called object initialization. After the construction method returns, an object is created, and its reference (address) can be published to the outside, which can be used to manipulate the object.
After the clone object is created, the new object can be filled with the same memory as the original clone object. When the new object is created, the new object can be filled with the same memory as the new object.
If the member variable of an object has an object, override the clone method, such as
class Employee implements Cloneable { public Object clone() throws CloneNotSupportedException { Employee cloned = (Employee) super.clone(); cloned.hireDay = (Date)hireDay.clone() return cloned; } }
toString()
Class name plus @ plus hash string
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
notify()
Wakes up a single thread waiting on the object.
@HotSpotIntrinsicCandidate public final native void notify();
notifyAll()
Wake up all threads waiting on the object.
@HotSpotIntrinsicCandidate public final native void notifyAll();
wait()
The current thread waits until another thread calls the notify() method or notifyAll() method of the object.
public final void wait() throws InterruptedException { wait(0L); }
wait(long timeoutMillis)
The current thread waits for up to timeoutMillis milliseconds. Can be awakened by the notify() method or the notifyAll() method.
public final native void wait(long timeoutMillis) throws InterruptedException;
wait(long timeoutMillis, int nanos)
Blocking the current thread timeoutMillis milliseconds, nanos(0-999999) nanoseconds. Can be awakened by the notify() method or the notifyAll() method. It can be seen that when the source code is blocked by more than one millisecond, it is equivalent to one millisecond.
public final void wait(long timeoutMillis, int nanos) throws InterruptedException { if (timeoutMillis < 0) { throw new IllegalArgumentException("timeoutMillis value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos > 0 && timeoutMillis < Long.MAX_VALUE) { timeoutMillis++; } wait(timeoutMillis); }
finalize()
When the garbage collection determines that there is no longer a reference to the object, the garbage collector calls the object on the object.
@Deprecated(since="9") protected void finalize() throws Throwable { }
Packaging
Basic data types and packaging classes
The object of each wrapper class can encapsulate a corresponding basic type of data, and provide some other useful methods. Once a wrapper class object is created, its content (the encapsulated basic type data value) cannot be changed
Reasons why the content cannot be changed
The values stored in all wrapper classes are of final type.
test
package JavaObjectTest; public class ObjectTest { public static void main(String[] args) { int m = 500; Integer obj = new Integer(m); // Manual packing, discarded after version 9 int n = obj.intValue(); // Manual unpacking Integer obj1 = 100; //Automatic packing m = obj1; //Automatic unpacking System.out.println(" "+m+ obj1 + obj + n); } }
Integer class
There are too many wrapper classes. Take Integer as an example to see the source code
It is found that there are many variables and functions, such as type conversion, simple comparison and so on.
Math class
Common functions
These functions or variables are of static type and can be called directly without creating an instance of the class.
Math.PI Recorded pi Math.E record e Constant of Math There are also some similar constants, which are commonly used in engineering mathematics. Math.abs Find the absolute value Math.sin Sine function Math.asin Inverse sine 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 Get the largest integer not less than a certain number Math.floor Get the largest integer not greater than a certain number Math.IEEEremainder Seeking remainder Math.max Find the largest of two numbers Math.min Find the smallest of two numbers Math.sqrt Find the square Math.pow Find any power of a number, Throw ArithmeticException Handling overflow exceptions Math.exp seek e Any power of Math.log10 Base 10 logarithm Math.log Natural logarithm Math.rint Find the nearest integer to a number (it may be larger or smaller than a number) Math.round Ibid., return int Type or long Type (returned by previous function) double Type) Math.random Returns a random number between 0 and 1
Date time class
Data class
Store date related information, some of which are transient Modification, cannot be persisted
SimpleDateFormat class
SimpleDateFormat allows you to choose any user-defined date and time format to run.
package JavaObjectTest; import java.text.SimpleDateFormat; import java.util.Date; public class ObjectTest { public static void main(String[] args) { Date dateNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss"); System.out.println("Current time is: " + ft.format(dateNow)); } }
Example of letter description
G era mark AD
y four digit year 2001
July or July
d date of one month 10
H a.m. / p.m. (1-12) format 12 hours
H hours of the day (0-23) 22
m minutes 30
s seconds 55
S milliseconds 234
E day of the week
D days of the year 360
F second wed. In July
w week of the year 40
W week of the month 1 a A.M./P.M. mark PM
k hours of the day (1-24)
K A.M./P.M. (0~11) format 10 hours
z Time Zone Eastern Standard Time
’Text Delimiter
"Single quote"`
Calendar Class
Calendar class is an abstract class. It implements the objects of specific subclasses in actual use. The process of creating objects is transparent to programmers. You only need to use getInstance method to create them.
test
package JavaObjectTest; import java.util.Calendar; public class ObjectTest { public static void main(String args[]) { Calendar c = Calendar.getInstance(); //The default is the current date System.out.println(c); } }
output
java.util.GregorianCalendar[time=1618042749377,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2021,MONTH=3,WEEK_OF_YEAR=15,WEEK_OF_MONTH=2,DAY_OF_MONTH=10,DAY_OF_YEAR=100,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=19,SECOND=9,MILLISECOND=377,ZONE_OFFSET=28800000,DST_OFFSET=0]
When I try to check the source code, I find that the analogy Date class is too complex and powerful. I won't delve into it for the time being. I'll look at it when I use it.
other
printf method of outputting date
code
package JavaObjectTest; import java.text.SimpleDateFormat; import java.util.Date; public class ObjectTest { public static void main(String args[]) { // Initialize Date object Date date = new Date(); //c. use of System.out.printf("All date and time information:%tc%n",date); //Use of f System.out.printf("year-month-Daily format:%tF%n",date); //d. use of System.out.printf("month/day/Year format:%tD%n",date); //Use of r System.out.printf("HH:MM:SS PM Format (12 hour system):%tr%n",date); } }
output
dormancy
code
cpppackage JavaObjectTest; import java.text.SimpleDateFormat; import java.util.Date; public class ObjectTest { public static void main(String args[]) { try { System.out.println(new Date( ) ); Thread.sleep(1000*3); // Sleep for 3 seconds System.out.println(new Date( ) ); } catch (Exception e) { System.out.println("Got an exception!"); } } }
result
String class
Bottom maintenance
The value of string is stored as an array of byte type:
Constructor and creation
String() //Initialize a newly created String object to represent a null character sequence. String(byte[] bytes) //Decode the specified byte array by using the default character set of the platform to construct a new String. String(byte[] bytes, Charset charset) //Construct a new String by decoding the specified byte array with the specified charset. String(byte[] bytes, int offset, int length) //A new String is constructed by decoding the specified byte subarray using the platform's default character set. String(byte[] bytes, int offset, int length, Charset charset) //Construct a new String by decoding the specified byte subarray with the specified charset. String(byte[] bytes, int offset, int length, String charsetName) //Construct a new String by decoding the specified byte subarray using the specified character set. String(byte[] bytes, String charsetName) //Construct a new String by decoding the specified byte array with the specified charset. String(char[] value) //Assign a new String to represent the character sequence currently contained in the character array parameter. String(char[] value, int offset, int count) //Assign a new String that contains characters from a sub array of character array parameters. String(int[] codePoints, int offset, int count) //Assign a new String that contains the characters of a subarray of Unicode code point array parameters. String(String original) //Initialize a newly created String object to represent a character sequence with the same parameters; In other words, the newly created String is a copy of the parameter String. String(StringBuffer buffer) //Allocates a new string that contains the sequence of characters currently contained in the string buffer parameter. String(StringBuilder builder) //Assigns a new string that contains the sequence of characters currently contained in the string generator parameters.
Two instantiation methods
- Direct assignment (String str = "hello"): only one heap memory space will be opened up and will be automatically pooled without garbage.
- Construction method (String str= new String("hello");): It will open up two heap memory spaces, and one of them will become garbage
It is recycled by the system and cannot automatically enter the pool. It needs to pass public String intern(); Method: manually enter the pool. - In the development process, the construction method will not be used for string instantiation.