equals(),hashcode(),克隆学习心得

时间:2023-03-08 17:51:31

equals(),hashcode(),克隆学习心得

其实在开发时候,很少去重写equals(),hashCode()方法,但是有些时候业务需要还是要重写。

注意:

重写equals()方法一定要重写hashCode()方法。

notes:

java中两个对象的比较,首先查看的就是一个对象的hashCode,可以把hashCode理解为索引,通过索引可以找到其对应下的内容,可能会有多个。

如果说两个对象的hashCode都不相等,那可以肯定这个对象不同。

equals() 相等的两个对象,其hashcode一定相等,hashcode相等的,equals不一定相等。

     why?   

      equals相等的两个对象,两者肯定来自同一个索引,所以说两者hashcode一定相等,但是hashcode相等,只能代表他们来自同一个索引,索引下的内容可以有很多,不一定多相同。例如:方向,方法两个词语,按照'方'字索引的话,两者索引是相同的,但是两者的具体内容确实不同的。

    克隆:

       java的8钟基本类型的克隆都是深度克隆,除此之外,如果一个对象中有引用其他对象,那就需要进行深度克隆。

      方法有两种:

      1:类实现 Serializable and Cloneable接口

在引用的对象中,调被引用对象的克隆方法,等到克隆的被引用对象,然后set it.

2: 通过序列化和反序列化

demo如下:前提类要实现Serializable接口

@Test
public void testClone() throws Exception {
Student student = new Student();
student.setSName("樱木小哥");
student.setAmount(new BigDecimal(10));
student.setAddress("嘻嘻背影");
Teacher teacher = new Teacher();
teacher.settName("灌篮高手");
teacher.setAddress("余杭区");
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("樱木小哥1");
student.setAddress("西湖区");
teacher.settName("灌篮高手2");
System.out.println(newStudent.toString());
System.out.println(byteArrayInputStream.available());
}