本章概括
本章包括以下几个Item:
- Item 8: 覆盖equals请遵守通用规定
- Item 9: 覆盖equals时一定要覆盖hashCode
- Item 10: 始终要覆盖toString()
- Item 11: 谨慎的覆盖clone
- Item 12: 考虑实现Comparable接口
由于个人的工作原因, 在实际工作之中, 仅仅接触过#3与#5, 从未考虑过覆盖equals()
与 clone()
, 因此这一章只读了 #3与#5
Item 10 : 始终要覆盖toString()
忽然发现, 这真的是一个非常方便非常好的建议! 比如我们有某个类, 比如Student :
1 2 3 4 5 6 7 8 9 10 |
public class Student { String name; Integer age; // getters and setters ... } // 某个初始化语句: Student s = new Student(); |
本文原创,原文链接:http://www.flyml.net/2017/02/06/effective-java-chapter-3/
如果我们在使用的过程之中, 直接System.out.print(s)
的结果会非常类似Student@15db9742
其中@
前面是类的名称, 后面的是hashCode.
一种比较推荐的做法, 是覆盖Student
类的toString() 方法, 比如下面:
1 2 3 4 5 6 7 8 9 10 11 12 |
public class Student { public String name; public Integer age; // getters and setters ... @Override public String toString() { return String.format("name: %s, age: %s", name, age); } } |
Item 12: 考虑实现Comparable接口
实现Comparable接口有什么好处呢?
最大的好处就是我们可以对一系列对象进行比较, 比如直接使用JDK里面实现的比较方法进行排序、选取极值等等。 比如:
1 |
Arrays.sort(a); |
那么, 什么时候需要实现这个接口呢?
当我们的类有非常明显的内在排序关系的时候, 就应该实现这个接口。比如年代
注意: 返回值不一定非要是1或者-1, 正负数都行. 但是需要是Integer的范围之内的值. 否则会发生溢出等等问题
本文为原创文章,转载请注明出处
原文链接:http://www.flyml.net/2017/02/06/effective-java-chapter-3/

文章评论