BigDecimal精度问题

注意运算要设置精度

image.png

精度不同equals返回false,要用compareTo

《Java实操避坑指南》视频 - 图2
equals 返回false
compareTo 返回true

equals & compareTo & hashCode

image.png
indexOf:使用equals方法比较
binnarySearch:使用compareTo方法比较
treeSet contains():会用到CompareTo()方法
hashset contains():用的 hashCode() 和 equals()

lombok的坑

@EqualsAndHashCode的callSupper=true

callSupper=true才能使lombok生成的equals方法包含父类字段。
image.png

序列化

多次序列化问题

  1. public class WriteTeacher {
  2. public static void main(String[] args) throws Exception {
  3. try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("teacher.txt"))) {
  4. Person person = new Person("路飞", 20);
  5. Teacher t1 = new Teacher("雷利", person);
  6. Teacher t2 = new Teacher("红发香克斯", person);
  7. //依次将4个对象写入输入流
  8. oos.writeObject(t1);
  9. oos.writeObject(t2);
  10. oos.writeObject(person);
  11. oos.writeObject(t2);
  12. }
  13. }
  14. }
  15. public class ReadTeacher {
  16. public static void main(String[] args) {
  17. try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("teacher.txt"))) {
  18. Teacher t1 = (Teacher) ois.readObject();
  19. Teacher t2 = (Teacher) ois.readObject();
  20. Person p = (Person) ois.readObject();
  21. Teacher t3 = (Teacher) ois.readObject();
  22. System.out.println(t1 == t2);
  23. System.out.println(t1.getPerson() == p);
  24. System.out.println(t2.getPerson() == p);
  25. System.out.println(t2 == t3);
  26. System.out.println(t1.getPerson() == t2.getPerson());
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }
  32. //输出结果
  33. //false
  34. //true
  35. //true
  36. //true
  37. //true

《Java实操避坑指南》视频 - 图5

  • 当程序试图序列化一个对象时,会先检查此对象是否已经序列化过,只有此对象从未(在此虚拟机)被序列化过,才会将此对象序列化为字节序列输出。
  • 如果此对象已经序列化过,则直接输出编号即可。