【 第10条:始终要覆盖toString】
其实这条是一种编程的规范,我们在定义bean的时候最好覆盖toString方法。
举例来说:人可以抽象为一个bean,里面有属性姓名、性别、升高、年龄。我们期望toString出来看到这些信息,而不是一串看不懂的DNA分子结构。
package com.effective.java;
public class Pepole {
private String name;
private String sex;
private float stature;
private int age;
public Pepole(String name, String sex, float stature, int age) {
super();
this.name = name;
this.sex = sex;
this.stature = stature;
this.age = age;
}
@Override
public int hashCode() {
int result=17;
result = 31*result+name.hashCode();
result = 31*result+sex.hashCode();
result = 31*result+Float.floatToIntBits(stature);
result = 31*result+age;
return result;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Pepole)) {
return false;
}
Pepole p = (Pepole) obj;
return this.getName().equals(p.getName()) && this.getSex().equals(p.getSex())
&& this.getStature() == p.getStature() && this.getAge() == p.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public float getStature() {
return stature;
}
public void setStature(float stature) {
this.stature = stature;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
System.out.println(new Pepole("upxiaofeng", "male", 1.72f, 30).toString());
得到如下结果:
com.effective.java.Pepole@d7f24154
覆盖重写toString方法:
@Override
public String toString() {
return "Pepole [name=" + name + ", sex=" + sex + ", stature=" + stature + ", age=" + age + "]";
}
得到我们期望的结果:
Pepole [name=upxiaofeng, sex=male, stature=1.72, age=30]
【 第11条:谨慎地覆盖clone】
这条在实际开发中本人用的也比较少。文章的作者告诉我们尽量不去覆盖。
可以用拷贝构造器或静态工厂方法来变相实现这个需求。
这里就不做赘述。
【 第12条:考虑实现Comparable接口】
其实在上篇文章中已经出现了问题,由于People没有实现Comparable接口导致使用TreeMap或者TreeSet的出现异常,程序无法成功编译。
作者告诉我们实现Comparable接口是一个良好的习惯。
具体实现也很简单,这里也不做赘述。
总结
本书的第三章讨论了关于object所有非final的方法以及Comparable接口compareTo的方法。
Object包含非final方法如下:
equals
hashcode
clone
toString
finalize
阐明了什么时候该覆盖以及需要注意优化的地方。