1. What methods do objects share
Object is the parent class of all classes. Any class inherits object by default.
- clone protection method: implement the shallow copy of the object. This method can be called only when the clonable interface is implemented. Otherwise, a clonnotsupportedexception exception will be thrown.
- equals method: if it is not overridden, it works the same as the = = sign in Object. Subclasses generally need to override this method.
- hashCode method: this method is used for hash lookup. It rewrites the equals method. Generally, it rewrites the hashCode method (we will explain it later). This method is often used in some collections with hash function.
- getClass method: This is the method of final annotation to obtain the runtime type.
- Wait method: make the current thread must be the owner of the object, that is, it has the lock of the object. The wait() method waits until it acquires a lock or is interrupted. Wait (long timeout) sets a timeout interval. If the lock is obtained within the specified time, it returns.
After calling this method, the current thread will go to sleep until the following time occurs:
- Another thread called the notify method of the object.
- The notifyAll method of the object was called by another thread.
- Another thread called interrupt to interrupt the thread.
- The time interval is up.
- At this point, the thread can be scheduled. If it is interrupted, an InterruptedException exception will be thrown.
Explanation:
- notify: indicates to wake up a thread waiting on the object;
- notifyAll: indicates to wake up all threads waiting on the object;
- toString: convert to a string. Generally, subclasses have overrides. Otherwise, print the handle.
2. The difference between hashCode() and equals()
It is mainly distinguished from two perspectives: one is performance and the other is reliability.
2.1. Since the equals() method can realize the function of comparison, why do you need hashCode()?
Because the contents of the rewritten equals() method are generally comprehensive and complex, so the efficiency is relatively low. When using the hashCode() method for comparison, you only need to compare the generated hash value, which is more efficient.
2.2. Since hashCode() is so efficient, why use equals?
Because hashCode() is not completely reliable, and sometimes the hashcodes generated by different objects will be the same (there are two reasons for the hash collision when put ting values into the HashMap set). Therefore, hashCode() can only be said to be reliable at some time, but not absolutely reliable. Therefore, we can draw two important conclusions, During the interview, as long as you can say these two conclusions and understand the principle:
- For two objects whose equals() method is equal, their hashCode() must be equal, that is, the comparison with equals() is absolutely reliable;
- For two objects whose hashCode() method is equal, their equals() is not necessarily equal, that is, hashCode() is not absolutely reliable.
2.3. Extension
1. Alibaba development specification clearly stipulates:
- As long as equals() is overridden, hashCode() must be overridden;
- Because Set stores non duplicate objects, it is judged according to hashCode() and equals(), so the objects stored by Set must override this method;
- If the custom object is used as the Map key, hashCode() and equals() must be overridden;
- String overrides hashCode() and equals() methods, so we can happily use string objects as key s.
2. When does it need to be rewritten?
- In general, hashCode() does not need to be overloaded. hashCode() can be overloaded only when the class needs to be placed in the collection of HashTable, HashMap, HashSet and other hash structures;
3. So why overload hashCode()?
- If you override equals (), for example, the implementation of object-based content, and leave the implementation of hashCode() unchanged, it is likely that some two objects are "equal" but hashCode is different.
In this way, when you use one of them as a key to save to HashMap, Hashtable or HashSet, and then find another key value with "equal" to find them, you can't find them at all.
4. Why is it that if equals is equal, hashCode must be equal, while hashCode is equal, but equals is not required?
- Because small memory blocks are accessed according to hashCode, hashcodes must be equal;
- HashMap obtains an object by comparing the hashCode of the key and the equals is true;
- The reason why hashcodes are equal, but equals can be different. For example, Object A and Object B have the attribute name, so take the name attribute as the key, and hashcodes are calculated in that way, which is equivalent to that name is a string "name", so hashcodes are definitely the same, but the two objects do not point to the same object in memory, so the content of the attribute is different, So equals is false.
5. Why hashCode?
- Small memory blocks can be quickly found through hashCode;
- Compare the equals method block by hashCode. When get ting, compare the hashcodes first. If the hashcodes are different, put them back to true directly to improve the efficiency.
3. What is the difference between light copy and deep copy?
3.1 shallow copy
(1) Definition
- All variables in the copied object contain the same values as the properties in the original object, and all references to other objects still point to the objects referenced in the original object. That is, a shallow copy of an object copies the master object, but does not copy the referenced object in the master object.
- In general, shallow copy copies only the objects under consideration, not the reference objects in the objects under consideration.
(2) Shallow copy instance:
-
Student
public class Student implements Cloneable { private String name; private int age; private Teacher teacher; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
-
Teacher
public class Teacher implements Cloneable { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
-
Test shallow shellfish ShallowCopy
public class ShallowCopy { public static void main(String[] args) throws CloneNotSupportedException { Teacher teacher = new Teacher(); teacher.setName("Lao Pang"); teacher.setAge(35); Student student1 = new Student(); student1.setName("Yisujun"); student1.setAge(21); student1.setTeacher(teacher); /** * Shallow copy a student1 */ Student student2 = (Student)student1.clone(); System.out.println("After copying******************"); System.out.println(student2.getName());//Yisujun System.out.println(student2.getAge());//21 System.out.println(student2.getTeacher().getName());//Lao Pang System.out.println(student2.getTeacher().getAge());//21 System.out.println("After modifying the teacher's attribute value******************"); teacher.setName("Lao Ge"); System.out.println(student2.getTeacher().getName());//Lao Ge } }
(3) Analysis principle
Result analysis: the two references student1 and student2 point to two different objects, but the two teachers referring to student1 and student2 point to the same teacher reference object in student1, so it is a shallow copy.
3.2 deep copy
(1) Definition
- Deep copy is a whole independent object copy. Deep copy copies all attributes and dynamically allocated memory pointed to by attributes. Deep copy occurs when an object is copied together with the object it refers to. Compared with shallow copy, deep copy is slow and expensive.
- In general, deep copy copies all the objects referenced by the object to be copied.
(2) Case analysis
The properties of Student and Teacher still use the above example, but the clone has been modified
- Teacher
//The Teacher class also needs to add the clone method @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }
- Student
@Override public Object clone() throws CloneNotSupportedException { //Shallow copy (one layer only) //return super.clone(); //Shallow copy (external class object) Student student = (Student)super.clone(); //Deep copy (internal class reference, also copy) student.setTeacher((Teacher)student.getTeacher().clone()); return student; }
- DeepCopy
public class DeepCopy { public static void main(String[] args) throws CloneNotSupportedException { Teacher teacher = new Teacher(); teacher.setName("Lao Pang"); teacher.setAge(35); Student student1 = new Student(); student1.setName("Yisujun"); student1.setAge(21); student1.setTeacher(teacher); /** * Shallow copy a student1 */ Student student2 = (Student)student1.clone(); System.out.println("After copying******************"); System.out.println(student2.getName());//Yisujun System.out.println(student2.getAge());//21 System.out.println(student2.getTeacher().getName());//Lao Pang System.out.println(student2.getTeacher().getAge());//21 System.out.println("After modifying the teacher's attribute value******************"); teacher.setName("Lao Ge"); System.out.println(student2.getTeacher().getName());//Lao Pang } }
(3) Analysis principle
- The two references student1 and student2 point to two different objects. The two references student1 and two teacher references in student2 point to two objects. However, the modification of the teacher object can only affect student1 object, so it is a deep copy.