【发布时间】:2022-01-23 17:00:55
【问题描述】:
我有以下简单的 Java 代码,
import lombok.EqualsAndHashCode;
@EqualsAndHashCode
public class Test{
}
当我查看生成的 delomboked 代码时,我看到以下内容:
public class Test {
public Test() {
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Test)) {
return false;
} else {
Test other = (Test)o;
return other.canEqual(this);
}
}
protected boolean canEqual(Object other) {
return other instanceof Test;
}
public int hashCode() {
int result = true;
return 1;
}
}
我不明白hashCode() 的实现。这是一个好的散列方法吗?为什么int result = true;没有编译问题?
我怀疑这与 hashCode() 是 native 有关,但我不明白为什么我会看到这个实现。
更新:我的主要问题是关于缺少编译错误。例如,如果我添加两个字段,我会:
import lombok.EqualsAndHashCode;
@EqualsAndHashCode
public class Test{
private String name;
public int age;
}
和
...
public int hashCode() {
int PRIME = true;
int result = 1;
int result = result * 59 + this.age;
Object $name = this.name;
result = result * 59 + ($name == null ? 43 : $name.hashCode());
return result;
}
...
【问题讨论】:
-
您是否检查过,当您将状态添加到您的类(即字段)时,hashCode 方法会发生什么?
-
为什么 result=true 会是编译器问题?有一个无意义的变量并不违法。最多是一个警告。至于它为什么这样做——如果你有实际的字段,很可能会使用它,而且他们没有打扰特殊的外壳,将它删除为无字段类。
-
@GabeSechan 因为声明的变量是
int而true是boolean,并且在java 中,与C(++) 不同,它们不匹配。我错了吗? (我在发布之前检查了这个,我得到了一个编译错误。)
标签: java lombok intellij-lombok-plugin