在线阅读
在处理必须关闭的资源时,使用 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();
}
}
当重写 equals 方法时,必须遵守它的通用约定。Object 的规范如下: equals 方法实现了一个等价关系(equivalence relation)。它有以下这些属性:
x.equals(x) 必须返回 true。y.equals(x) 返回 true 时 x.equals(y) 必须返回 true。x.equals(y) 返回 true,y.equals(z) 返回 true,则 x.equals(z) 必须返回 true。x.equals(y) 的多次调用必须始终返回 true 或始终返回 false。x.equals(null) 必须返回 false。// 自反性
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 这样的集合中正常工作。