use*_*911 3 java equals hashcode
如果我有一个地图和一个对象作为地图键,是默认的哈希和等于方法吗?
class EventInfo{
private String name;
private Map<String, Integer> info
}
Run Code Online (Sandbox Code Playgroud)
然后我想创建一个地图:
Map<EventInfo, String> map = new HashMap<EventInfo, String>();
Run Code Online (Sandbox Code Playgroud)
我是否必须显式实现hashCode()和equals()?谢谢.
是的你是.HashMap通过计算密钥的哈希码并将其用作基点来工作.如果hashCode函数未被覆盖(由你),那么它将使用内存地址,equals并将与之相同==.
如果您在Eclipse中,它将为您生成它们.单击Source菜单→ Generate hashCode()和equals().
如果您没有Eclipse,那么这里应该有一些.(我在Eclipse中生成了这些,如上所述.)
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((info == null) ? 0 : info.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 (!(obj instanceof EventInfo)) {
return false;
}
EventInfo other = (EventInfo) obj;
if (info == null) {
if (other.info != null) {
return false;
}
} else if (!info.equals(other.info)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)