几天前,我们在公司内部改用Java 7-终于! Jay\o/因此,我发现了Objects
类,并惊讶于实现hashCode()
和equals()
方法的时间有多短,与默认情况下eclipse生成的代码相比,减少了许多波特尔板代码(ALT + SHIFT + S-> H )。
我想知道是否可以更改eclipse生成的hashCode()
和equals()
的默认行为?
我很想看看这个:
@Override
public int hashCode()
{
return Objects.hash(one, two, three, four/*, ...*/);
}
代替这个:
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((one == null) ? 0 : one.hashCode());
result = prime * result + ((two == null) ? 0 : two.hashCode());
result = prime * result + ((three == null) ? 0 : three.hashCode());
result = prime * result + ((four== null) ? 0 : four.hashCode());
// ...
return result;
}
equals()
也是如此。 This is the article我从这里得到的。有什么想法如何最好地实现这一目标吗?
最佳答案
现在已经在Eclipse中实现了使用Java 7 hashCode
类生成equals
和Objects
的功能。早在2018年8月,我就在功能请求424214上进行工作,此后不久我的贡献便被合并到JDT UI代码库中(请参阅commit f543cd6)。
这是Source> Generate hashCode()and equals ...工具中新选项的概述:
它已于2018年9月在Eclipse 4.9中正式发布。只需下载最新版本的Eclipse(可在here中找到下载),或通过以下更新站点安装最新的可用软件:
http://download.eclipse.org/releases/latest
除了此新功能,现在还可以更巧妙地处理阵列。在以前不正确地使用标准Arrays.deepHashCode
和Arrays.deepEquals
替代品的许多情况下,该代将使用Arrays.hashCode
和Arrays.equals
方法。