一些由框架填充的类(如beans)。因此,不能保证所有字段都设置了。
例如:被标记为@Entity的类通常具有Integer id字段。hashCode可以写成:
但防御性的代码可能看起来像:
例如:被标记为@Entity的类通常具有Integer id字段。hashCode可以写成:
public int hashCode() {
return id.hashCode();
}
但防御性的代码可能看起来像:
public int hashCode() {
return (id != null) ? id.hashCode() : 0;
}
我需要在hashCode
和equals
函数中编写检查null或用try { ... } catch (Exception e)
包围代码吗?
我没有为这种情况下的防御性编程提供论据,因为它会隐藏将不一致的对象放入集合并导致迟到的错误。我的立场是否有误?
更新 我编写了这样的代码:
import java.util.*;
class ExceptionInHashcode {
String name;
ExceptionInHashcode() { }
ExceptionInHashcode(String name) { this.name = name; }
public int hashCode() {
// throw new IllegalStateException("xxx");
return this.name.hashCode();
}
public static void main(String args[]) {
Hashtable list = new Hashtable();
list.put(new ExceptionInHashcode("ok"), 1);
list.put(new ExceptionInHashcode(), 2); // fail
System.out.println("list.size(): " + list.size());
}
}
并运行它:
java -classpath . ExceptionInHashcode
Exception in thread "main" java.lang.NullPointerException
at ExceptionInHashcode.hashCode(ExceptionInHashcode.java:12)
at java.util.Hashtable.hash(Hashtable.java:262)
at java.util.Hashtable.put(Hashtable.java:547)
at ExceptionInHashcode.main(ExceptionInHashcode.java:18)
我认为如果对象处于错误状态,早期发现错误比返回零更好...
hashCode
实现破坏了Object#hashCode
的约定:在 Java 应用程序执行期间,每当它在同一对象上被多次调用时,只要在 equals 比较中使用的对象信息未被修改,hashCode
方法必须始终返回相同的整数。这个整数不需要在同一应用程序的不同执行之间保持一致。 - Luiggi MendozaIllegalStateException
而不是让NullPointerException
直接冒泡。对我来说,在别人的代码中遇到NullPointerException
就像嗅到了一个错误,但IllegalStateException
告诉我“按照设计,你不允许这样做(尚未)”。 - lc.