在线阅读

effctive-java-3rd-chinese

Methods Common to All Object


1. 使用 try-with-resources 代替 try-finally 语句

在处理必须关闭的资源时,使用 try-with-resources 语句替代 try-finally 语句。 生成的代码更简洁,更清晰,并且生成的异常更有用,如下:

// try-finally 版本代码
static String firstLineOfFile(String path) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        br.close();
    }
}
// try-with-resources 版本代码
static String firstLineOfFile(String path) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
       return br.readLine();
    }
}

2. 重写 equals 方法需要遵守的约定

当重写 equals 方法时,必须遵守它的通用约定。Object 的规范如下: equals 方法实现了一个等价关系(equivalence relation)。它有以下这些属性:

// 自反性
x.equals(x) = true

// 对称性
if y.equals(x) 
	then x.equals(y) = true

// 传递性
if x.equals(y) and y.equals(z) 
	then x.equals(z) = true

// 一致性
if x.equals(y) 
	then handle(x,y) , x.equals(y) = true

// 非空性
x.equals(null) = false

当重写了一个类的 equals 后,一定要重写 hashCode 方法。否则会阻止该类在 HashMap、HashSet 这样的集合中正常工作。