Equals (), hashcode (), Cloning learning experience
In fact, in the development time, rarely to rewrite the Equals (), Hashcode () method, but sometimes the business needs to be rewritten.
Attention:
Overriding the Equals () method is sure to override the Hashcode () method.
Notes
The comparison of two objects in Java, the first is to look at the hashcode of an object, you can interpret hashcode as an index, the index can find its corresponding content, there may be more than one.
If the hashcode of two objects are not equal, it is certain that the object is different.
equals () is equal to two objects whose hashcode must be equal, Hashcode equal, and equals not necessarily equal.
Why ?
equals two objects, the two must come from the same index, so the two hashcode must be equal, but the hashcode is equal, only on behalf of them from the same index, the index can have a lot of content, not necessarily the same. For example: direction, method Two words, according to the ' Square ' word index, the two indexes are the same, but the concrete content of the two is really different.
Cloning:
Java's 8-clock basic type of cloning is deep cloning, in addition, if an object has references to other objects, it will require deep cloning.
There are two ways of doing this:
1: Class implementation Serializable and Cloneable interface
In the referenced object, tune the cloned method of the referenced object, wait until the cloned object is referenced, and then set it.
2: by serialization and deserialization
The demo is as follows: prerequisite class to implement Serializable interface
@Test
public void Testclone () throws Exception {
Student Student = new Student ();
Student.setsname ("Cherry wood Brother");
Student.setamount (New BigDecimal (10));
Student.setaddress ("hehe back");
Teacher Teacher = new Teacher ();
Teacher.settname ("Slam Dunk Master");
Teacher.setaddress ("Yuhang");
Student.setteacher (teacher);
System.out.println (Student.tostring ());
Bytearrayoutputstream Bytearrayoutputstream = new Bytearrayoutputstream ();
ObjectOutputStream ObjectOutputStream = new ObjectOutputStream (bytearrayoutputstream);
Objectoutputstream.writeobject (student);
Bytearrayinputstream Bytearrayinputstream = new Bytearrayinputstream (Bytearrayoutputstream.tobytearray ());
System.out.println (Bytearrayinputstream.available ());
ObjectInputStream ObjectInputStream = new ObjectInputStream (bytearrayinputstream);
Student newstudent = (Student) objectinputstream.readobject ();
Objectinputstream.close ();
Objectoutputstream.close ();
Bytearrayinputstream.close ();
Objectoutputstream.close ();
System.out.println (Newstudent.tostring ());
Student.setsname ("cherry wood 1");
Student.setaddress ("West L. District");
Teacher.settname ("Slam Dunk 2");
System.out.println (Newstudent.tostring ());
System.out.println (Bytearrayinputstream.available ());
}
Equals (), hashcode (), Cloning learning experience