【发布时间】:2013-07-17 23:28:14
【问题描述】:
我使用 eclipse 来生成对象的 hashCode 和 equals 方法的覆盖,这产生了一些关于 hashCode 覆盖的问题。下面的 hashCode() 是否正确?
问题:
-为什么eclipse会生成两行result =代码?我认为将这两个结果加在一起是合适的。任何想法为什么它们是单独的任务?
-最终的 int 素数可以是任何素数吗?
-int 结果应该始终为 1 吗?
public class Overrider {
private Long id;
private String name;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Overrider other = (Overrider) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
【问题讨论】:
-
它不是重复的,我想知道 Eclipse 插入的内容是否有效,因为它与我见过的其他示例不同
-
"知道为什么它们是单独的任务吗?" 因为可读代码比将大量逻辑塞进一行而产生的垃圾要好得多。
标签: java