在用Java重写equals()和hashcode()方法时,为什么不经常使用这些方法:
public int hashCode() {
return (int) this.hashCode();
}甚至上面加上了一个素数:
public int hashCode() {
final int prime = 31; //31 is a common example
return (int) prime * this.hashCode();
}这是一种糟糕的做法,还是根本不起作用?
发布于 2014-04-22 10:21:41
方法:
public int hashCode() {
return (int) this.hashCode();
}将导致StackOverflowError,因为它会无限地返回自身,除非您用super替换this。第二种方法也有同样的问题。
此外,将int类型的值转换为int也是无用的。
如果您没有为方法提供任何有用的新内容,就不要覆盖它。
https://stackoverflow.com/questions/23216707
复制相似问题