Article directory
Common methods of the Object class can be divided into the following categories:
1. Object creation and destruction methods:
- Object(): Constructor, creates a new object.
- finalize(): The method called by the garbage collector, executed before the object is destroyed.
2. How to obtain object information:
- getClass(): Get the runtime class of the object.
- hashCode(): Returns the hash code value of the object.
- toString(): Returns the string representation of the object.
3. Object comparison method:
- equals(Object obj): Compare objects for equality.
- compareTo(T obj): The order of comparison objects.
- clone(): Creates and returns a copy of the object.
4. Thread related methods:
- wait(): Causes the current thread to wait until other threads call the object's notify() or notifyAll() method.
- notify(): Wake up one of the threads waiting for the object.
- notifyAll(): Wake up all threads waiting for the object.
5. Lock related methods:
- synchronized: used to modify code blocks or methods to implement synchronization locks.
6. Use cases:
Here are usage examples for each method:
1. Object creation and destruction methods:
Object obj = new Object();
obj.finalize();
2. Method to obtain object information:
Class<?> clazz = obj.getClass();
int hashCode = obj.hashCode();
String str = obj.toString();
3. Object comparison method:
boolean isEqual = obj1.equals(obj2);
int compareResult = obj1.compareTo(obj2);
Object objCopy = obj.clone();
4. Thread related methods:
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (obj) {
obj.notify();
}
synchronized (obj) {
obj.notifyAll();
}
5. Lock related methods:
public synchronized void synchronizedMethod() {
// synchronized 修饰的方法
}
public void synchronizedBlock() {
synchronized (this) {
// synchronized 修饰的代码块
}
}