一些类由框架(如 bean)填充。所以你不能保证所有字段都已设置。
查看示例:标记为的类@Entity
通常有Integer id
field. hashCode
可以写成:
public int hashCode() {
return id.hashCode();
}
但防御代码可能如下所示:
public int hashCode() {
return (id != null) ? id.hashCode() : 0;
}
我是否需要编写空代码或环绕代码检查try { ... } catch (Exception e)
in hashCode
and equals
功能?
我没有理由支持这种情况下的防御性编码,因为它隐藏了将不一致的对象放入集合中并导致后期错误。我这个立场有错吗?
UPDATE我写了这样的代码:
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)
我认为如果对象处于错误状态,我可以尽早发现错误而不是返回零......